Header Ads

MEAN Stack (Insert data from nodejs)

MEAN Stack (Insert 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



In the Previous blog, we have seen the creating an angular project and select a table data from MongoDB by using a Nodejs and Expressjs. To check the selection of data in table Click here.

Integrate the Expressjs

Integrate the Expressjs, morgan, router path. Expressjs are used to integrate nodejs and angular project.

// Express
let express = require("express");
const app = express.Router();
const path = require("path");

// Morgan
let 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 Database
let 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");

Insert a data

If the database is open and inserts a data in table or records and use it in the Angular project.

//Create User
app.post("/employee/create", (req, res, next) => {
   data={firstname:req.body.firstname,lastname:req.body.lastname,dob:req.body.dob};
    Employee.create(data, (err, user)=>{
        if (err) return res.json(err)
        else return res.json(user)
    })
})

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;

  createUser(data) {
       let headers = new Headers({ 'Content-Type': 'application/json' });
       let options = new RequestOptions({ headers: headers });
       let loginvalue;
       //observable
       return this.http.post("api/employee/create",data)
       .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>;
 
    Create(){
         var data={firstname:this.firstname,lastname:this.lastname,dob:this.dob};
        //observable http link
        this.dataservice.createUser(data).subscribe(res => {
           this.loading = false;
          }, error => {
                this.loading = false;
            });
    }


UI page

         <button type="button" class="btn btn-info" (click)="Create()">Create</button>
<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>

when the insertion process is finished then the MongoDB  and angular project looks like




Post a Comment

0 Comments