Header Ads

MEAN Stack (Delete data from nodejs)

MEAN Stack (Delete 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");

Delete a data

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

//Delete User
app.delete("/employee/:id", (req, res, next) => {
    var id=req.params.id;
    Employee.findOneAndRemove({_id:id}, (err, user)=>{
        if (err) return res.json(err)
        else return res.json(true)
    })
})

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;
 deleteUser(id){
       let headers = new Headers({ 'Content-Type': 'application/json' });
       let options = new RequestOptions({ headers: headers });
       let loginvalue;
       //observable
       return this.http.delete("api/employee/"+id)
       .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>;
 delete(id){
       this.dataservice.deleteUser(id).subscribe(res => {
           this.loading = false;
           alert("Employee deleted successfully")
           }, 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 updating process is finished then angular project looks like




Post a Comment

1 Comments

  1. The best MEAN Stack Training in Gurgaon offer hands-on experience with real-world projects, so you can gain practical experience and build a strong foundation in MEAN stack. In addition, many training institutes offer job placement assistance to help students find jobs after completing their training

    ReplyDelete