MEAN Stack (Select Table)
MEAN is a collection of javascript-based technologies. To develop the Angular web application, to integrate Angular as front end and node.js as a back end. MEAN is a full development toolkit used to develop from the client side and server side to database.
Stack for developing the MEAN stack
- MongoDB
- Angular
- Nodejs
- Expressjs
Installing Nodejs
To access the Node Package Manager(NPM) first of all, install the Nodejs. If the Nodejs is installed, check whether the Nodejs is installed. Open the command prompt and console it. To install node.js visit the Nodejs.org
Node -v
Install Angular
To create an Angular project first, install the angular-cli. The installation was done by command prompt. verify the Angular install
npm install @angular/cli -g
Create angular project
Once installed, create an angular project and run the angular project. The front end is created in the angular project.
ng new projectnamecd projectname
Build a project
we are using express server so it will work only in dist folder. if the project created then build the project and it stored in dist folder.
ng build
Setting up Expressjs
To setting up Expressjs, first of all, install the npm package to use in an angular project. Open the command prompt and run the command code.
npm install express body-parser --save
This will install the Express server package and body-parser. Open the project and create the server.js file and paste it.
const express = require('express');const bodyParser = require('body-parser');const path = require('path');const http = require('http');const app = express();const api = require('./server/routes/api');app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: false}));app.use(express.static(path.join(__dirname, 'dist')));app.use('/api', api);app.get('*', (req, res) => {res.sendFile(path.join(__dirname, 'dist/index.html'));});//Set Portconst port = process.env.PORT || '3000';app.set('port', port);const server = http.createServer(app);server.listen(port, () => console.log(`Running on localhost:${port}`));
Setting up MongoDB
You can set up the MongoDB locally(install the MongoDB, preferred package for os) or visit the mlab.com to use as online.
Create a new collection and insert a new record and use it in the angular project.
Setting up Mongoose
Mongoose is used as NPM package manager to interact with MongoDB in nodejs. Open the command prompt and run the following code
npm install mongoose
Create the following project structure and create a new file as api.js. Open the api.js in the editor. Now we can use select and insert query in mongoose.
Integrate the Expressjs
Integrate the Expressjs, morgan, router path. Expressjs are used to integrate nodejs and angular project.
// Expresslet express = require("express");const app = express.Router();const path = require("path");// Morganlet morgan = require("morgan");app.use(morgan('dev'));
Create the new database in MongoDB and integrate and open an existing database in mongoose package.
// Connect// Mongo Databaselet mongoose = require("mongoose");mongoose.connect('mongodb://name');let EmployeeDet = new mongoose.Schema({firstname: { type: String, require: true },lastname: { type: String, require: true },dob: { type: String, require: true }})mongoose.model("employee", EmployeeDet);let Employee = mongoose.model("employee");
If the database is open and selects the all data in table or records and use it in the Angular project.
// Get Usersapp.get("/employee", (req, res, next) => {Employee.find({}, (err, users)=>{return res.json(users);})})
Fetching Data From Angular
Right now we are accessing only the MongoDB, but we must integrate into the angular project by creating service file for communicating with the API.
ng g service servicename
Open up the new file that was generated /src/app/data.service.ts and paste it.
import { Injectable } from '@angular/core';import { Http, Headers, RequestOptions } from '@angular/http';import 'rxjs/add/operator/map';import 'rxjs/add/operator/catch';import { Observable } from 'rxjs/Observable';@Injectable()export class DataService {constructor(private http:Http) { }result:any;getUsers() {let headers = new Headers({ 'Content-Type': 'application/json' });let options = new RequestOptions({ headers: headers });let loginvalue;//observablereturn this.http.get("api/employee").map(res => res.json()).map((res) => {loginvalue=res;if (res == null) {return loginvalue;}return loginvalue;}).catch(this.handleError)}
app.component.ts
first of all, import data service page in app.component.ts page and create a local variable for data services in the constructor and call the API from ts page
import { Component, OnInit, ViewChild } from '@angular/core';
import { DataService } from '../data.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private dataservice:DataService,private popup:Popup) { }
users: Array<any>;
ngOnInit() {
this.dataservice.getUsers().subscribe(res => {
this.users = res
console.log("user",this.users);
this.loading = false;
}, error => {
this.loading = false;
});
}
UI page
<table class="table table-bordered">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>DOB</th>
<th></th>
</tr>
</thead>
<tbody>
<tr *ngFor="let s of users; let i=index ">
<td>{{s.firstname}}</td>
<td>{{s.lastname}}</td>
<td>{{s.dob}}</td>
<td><button type="button" class="btn btn-primary" (click)="edit()">Edit</button>
<button type="button" class="btn btn-danger" (click)="delete()">Delete</button></td>
</tr>
</tbody>
</table>
0 Comments