CRUD Operations Using Web API, MongoDB, And Angular 7

Introduction

 
MongoDB is a NoSQL, free, open source, high-performance, and cross-platform document-oriented database. It is called "Not Only SQL" or "non SQL" database as well.
 
MongoDB is developed by the 10gen company that is now called MongoDB Inc. MongoDB is written in C++ language and it stores data in flexible, JSON like format with a dynamic schema. In my previous articles on MongoDB, I have explained about the basic functions of MongoDB, including insert, update, delete operations.
 
You can check my previous articles on MongoDB here.

Prerequisites

  • We should have the basic knowledge of Angular, MongoDB, and Web API.
  • The Visual Studio Code IDE should be installed.
  • Robo 3T or Studio 3T should be installed.

This article covers -

  • How to create a database and collection in MongoDB
  • How to create a Web API Project
  • How to create Angular 7 Project
    • Install Bootstrap
    • Creating Components in Angular 7 project
    • Creating Class in Angular 7 project
    • Creating Service in Angular 7 project
    • Add Routing
    • Implement Searching and Paging 

Create a database and collection in MongoDB

MongoDB environment setup
 
Check how to set up the MongoDB environment and Robo 3T, from here.
 
Step 1
 
Now, open Robo 3T and connect to the local server.
 
 CRUD Operations Using Web API, MongoDB And Angular 7
 
Step 2 
 
Create a database with the name "employee" using Robo 3T (Check Link).
 

Create a Web API project

Step 1
 
Open Visual Studio and create a new project.
 
CRUD Operations Using Web API, MongoDB And Angular 7 
 
Change the name to CrudWithMongoDB.
 
CRUD Operations Using Web API, MongoDB And Angular 7
 
Choose the template as Web API.
 
 
Step 2
 
Now, add the MongoDB Driver for C# using NuGet Package Manager.
 
Go to Tools>>NuGet Package Manager >> Manage NuGet package for Solution.
 
CRUD Operations Using Web API, MongoDB And Angular 7
 
Step 3
 
Right-click the Models folder and add two classes - Employee and Status respectively. Now, paste the following codes in these classes respectively.
 
Add the required namespaces in the Employee class.
  1. using MongoDB.Bson;  
  2. using MongoDB.Bson.Serialization.Attributes;  
Employee class
  1. public class Employee  
  2.    {  
  3.        [BsonRepresentation(BsonType.ObjectId)]  
  4.        public String Id { getset; }  
  5.        public string Name { getset; }  
  6.        public string  { getset; }  
  7.        public string Address { getset; }  
  8.        public string City { getset; }  
  9.        public string Country { getset; }  
  10.    }  
Status class
  1. public class Status  
  2.    {  
  3.        public string Result { setget; }  
  4.        public string Message { setget; }  
  5.    }  
Step 4
 
Now, add a connection string in the web.config file and add the following line in the App Settings section of that file.
  1. <add key="connectionString" value="mongodb://localhost"/>    
Step 5
 
Right-click on the Controllers folder and add a new controller. Name it as "Emp controller".
 
Add the following namespaces in the Emp controller.
  1. using MongoDB.Driver;  
  2. using MongoDB.Bson;  
  3. using CrudWithMongoDB.Models;  
Now, add a method to insert data into the database for inserting employee details.
  1. [Route("InsertEmployee")]  
  2.        [HttpPost]  
  3.        public object Addemployee(Employee objVM)  
  4.        {  
  5.            try  
  6.            {   ///Insert Emoloyeee  
  7.                #region InsertDetails  
  8.                if (objVM.Id == null)  
  9.                {  
  10.                    string constr = ConfigurationManager.AppSettings["connectionString"];  
  11.                    var Client = new MongoClient(constr);  
  12.                    var DB = Client.GetDatabase("Employee");  
  13.                    var collection = DB.GetCollection<Employee>("EmployeeDetails");  
  14.                    collection.InsertOne(objVM);  
  15.                    return new Status  
  16.                    { Result = "Success", Message = "Employee Details Insert Successfully" };  
  17.                }  
  18.                #endregion  
  19.                ///Update Emoloyeee  
  20.                #region updateDetails  
  21.                else  
  22.                {  
  23.                    string constr = ConfigurationManager.AppSettings["connectionString"];  
  24.                    var Client = new MongoClient(constr);  
  25.                    var Db = Client.GetDatabase("Employee");  
  26.                    var collection = Db.GetCollection<Employee>("EmployeeDetails");  
  27.   
  28.                    var update = collection.FindOneAndUpdateAsync(Builders<Employee>.Filter.Eq("Id", objVM.Id), Builders<Employee>.Update.Set("Name", objVM.Name).Set("Department", objVM.Department).Set("Address", objVM.Address).Set("City", objVM.City).Set("Country", objVM.Country));  
  29.   
  30.                    return new Status  
  31.                    { Result = "Success", Message = "Employee Details Update Successfully" };  
  32.                }  
  33.                #endregion  
  34.            }  
  35.   
  36.            catch (Exception ex)  
  37.            {  
  38.                return new Status  
  39.                { Result = "Error", Message = ex.Message.ToString() };  
  40.            }  
  41.   
  42.        }  
 Add a new method to delete employee details.
  1. #region DeleteEmployee  
  2.      [Route("Delete")]  
  3.      [HttpGet]  
  4.      public object Delete(string id)  
  5.      {  
  6.          try  
  7.          {  
  8.              string constr = ConfigurationManager.AppSettings["connectionString"];  
  9.              var Client = new MongoClient(constr);  
  10.              var DB = Client.GetDatabase("Employee");  
  11.              var collection = DB.GetCollection<Employee>("EmployeeDetails");  
  12.              var DeleteRecored = collection.DeleteOneAsync(  
  13.                             Builders<Employee>.Filter.Eq("Id", id));  
  14.              return new Status  
  15.              { Result = "Success", Message = "Employee Details Delete  Successfully" };  
  16.   
  17.          }  
  18.          catch (Exception ex)  
  19.          {  
  20.              return new Status  
  21.              { Result = "Error", Message = ex.Message.ToString() };  
  22.          }  
  23.   
  24.      }  
  25.      #endregion  
Add a method to get Employee details.
  1. #region Getemployeedetails  
  2.        [Route("GetAllEmployee")]  
  3.        [HttpGet]  
  4.        public object GetAllEmployee()  
  5.        {  
  6.            string constr = ConfigurationManager.AppSettings["connectionString"];  
  7.            var Client = new MongoClient(constr);  
  8.            var db = Client.GetDatabase("Employee");  
  9.            var collection = db.GetCollection<Employee>("EmployeeDetails").Find(new BsonDocument()).ToList();  
  10.            return Json(collection);  
  11.   
  12.        }  
  13.        #endregion  
 Add a method to get Employee details by Id.
  1. #region EmpdetaisById  
  2.      [Route("GetEmployeeById")]  
  3.      [HttpGet]  
  4.      public object GetEmployeeById(string id)  
  5.      {  
  6.          string constr = ConfigurationManager.AppSettings["connectionString"];  
  7.          var Client = new MongoClient(constr);  
  8.          var DB = Client.GetDatabase("Employee");  
  9.          var collection = DB.GetCollection<Employee>("EmployeeDetails");  
  10.          var plant = collection.Find(Builders<Employee>.Filter.Where(s => s.Id == id)).FirstOrDefault();  
  11.          return Json(plant);  
  12.   
  13.      }  
  14.      #endregion  
Here is the complete Emp controller code.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using MongoDB.Driver;  
  8. using MongoDB.Bson;  
  9. using CrudWithMongoDB.Models;  
  10. using System.Configuration;  
  11.   
  12. namespace CrudWithMongoDB.Controllers  
  13. {  
  14.     [RoutePrefix("Api/Employee")]  
  15.     public class EmpController : ApiController  
  16.     {  
  17.         [Route("InsertEmployee")]  
  18.         [HttpPost]  
  19.         public object Addemployee(Employee objVM)  
  20.         {  
  21.             try  
  22.             {   ///Insert Emoloyeee  
  23.                 #region InsertDetails  
  24.                 if (objVM.Id == null)  
  25.                 {  
  26.                     string constr = ConfigurationManager.AppSettings["connectionString"];  
  27.                     var Client = new MongoClient(constr);  
  28.                     var DB = Client.GetDatabase("Employee");  
  29.                     var collection = DB.GetCollection<Employee>("EmployeeDetails");  
  30.                     collection.InsertOne(objVM);  
  31.                     return new Status  
  32.                     { Result = "Success", Message = "Employee Details Insert Successfully" };  
  33.                 }  
  34.                 #endregion  
  35.                 ///Update Emoloyeee  
  36.                 #region updateDetails  
  37.                 else  
  38.                 {  
  39.                     string constr = ConfigurationManager.AppSettings["connectionString"];  
  40.                     var Client = new MongoClient(constr);  
  41.                     var Db = Client.GetDatabase("Employee");  
  42.                     var collection = Db.GetCollection<Employee>("EmployeeDetails");  
  43.   
  44.                     var update = collection.FindOneAndUpdateAsync(Builders<Employee>.Filter.Eq("Id", objVM.Id), Builders<Employee>.Update.Set("Name", objVM.Name).Set("Department", objVM.Department).Set("Address", objVM.Address).Set("City", objVM.City).Set("Country", objVM.Country));  
  45.   
  46.                     return new Status  
  47.                     { Result = "Success", Message = "Employee Details Update Successfully" };  
  48.                 }  
  49.                 #endregion  
  50.             }  
  51.   
  52.             catch (Exception ex)  
  53.             {  
  54.                 return new Status  
  55.                 { Result = "Error", Message = ex.Message.ToString() };  
  56.             }  
  57.   
  58.         }  
  59.  
  60.         #region Getemployeedetails  
  61.         [Route("GetAllEmployee")]  
  62.         [HttpGet]  
  63.         public object GetAllEmployee()  
  64.         {  
  65.             string constr = ConfigurationManager.AppSettings["connectionString"];  
  66.             var Client = new MongoClient(constr);  
  67.             var db = Client.GetDatabase("Employee");  
  68.             var collection = db.GetCollection<Employee>("EmployeeDetails").Find(new BsonDocument()).ToList();  
  69.             return Json(collection);  
  70.   
  71.         }  
  72.         #endregion  
  73.         #region EmpdetaisById  
  74.         [Route("GetEmployeeById")]  
  75.         [HttpGet]  
  76.         public object GetEmployeeById(string id)  
  77.         {  
  78.             string constr = ConfigurationManager.AppSettings["connectionString"];  
  79.             var Client = new MongoClient(constr);  
  80.             var DB = Client.GetDatabase("Employee");  
  81.             var collection = DB.GetCollection<Employee>("EmployeeDetails");  
  82.             var plant = collection.Find(Builders<Employee>.Filter.Where(s => s.Id == id)).FirstOrDefault();  
  83.             return Json(plant);  
  84.   
  85.         }  
  86.         #endregion  
  87.         #region DeleteEmployee  
  88.         [Route("Delete")]  
  89.         [HttpGet]  
  90.         public object Delete(string id)  
  91.         {  
  92.             try  
  93.             {  
  94.                 string constr = ConfigurationManager.AppSettings["connectionString"];  
  95.                 var Client = new MongoClient(constr);  
  96.                 var DB = Client.GetDatabase("Employee");  
  97.                 var collection = DB.GetCollection<Employee>("EmployeeDetails");  
  98.                 var DeleteRecored = collection.DeleteOneAsync(  
  99.                                Builders<Employee>.Filter.Eq("Id", id));  
  100.                 return new Status  
  101.                 { Result = "Success", Message = "Employee Details Delete  Successfully" };  
  102.   
  103.             }  
  104.             catch (Exception ex)  
  105.             {  
  106.                 return new Status  
  107.                 { Result = "Error", Message = ex.Message.ToString() };  
  108.             }  
  109.   
  110.         }  
  111.         #endregion  
  112.     }  
  113. }  
Step 6
 
Now, let's enable CORS. Go to Tools, open NuGet Package Manager, search for Cors and install the "Microsoft.Asp.Net.WebApi.Cors" package.
 
CRUD Operations Using Web API, MongoDB And Angular 7
 
Open Webapiconfig.cs and add the following lines.
  1. EnableCorsAttribute cors = new EnableCorsAttribute("*""*""*");    
  2. config.EnableCors(cors);    

Create Angular 7 Project

 
Step 1
 
Create an Angular 7 project with the name "CrudwithMongoDB" by using the following command.
 ng new CrudwithMongoDB
 
Step 2
 
Open Visual Studio Code, open the newly created project and add bootstrap to this project.
 npm install bootstrap --save
 
Step 3
 
Now, create two components for - displaying the employee list page and adding a new employee page respectively. To create the components, open terminal and use the following commands.
ng g c employee ng g c addemployee
 
Step 4 
 
Create a class named "employee", by using the following command.
ng g class employee
 
Add the required properties in the class.
  1. export class Employee {  
  2.     Id: string;  
  3.     Name: string;  
  4.     Department: string;  
  5.     Address: string;  
  6.     City: string;  
  7.     Country: string;  
  8. }  
Step 5
 
Create a service to call the Web API.
ng g s emprecord
 
Step 6
 
Open the emprecord service and import required packages and classes. Add the following lines of code in the emprecord.service.ts file.
  1. import { Injectable } from '@angular/core';  
  2. import { Observable } from "rxjs";  
  3. import {HttpHeaders, HttpClient } from "@angular/common/http";  
  4. import { Employee } from "../app/employee";  
  5. @Injectable({  
  6.   providedIn: 'root'  
  7. })  
  8. export class EmprecordService {  
  9.    Url="http://localhost:14026/Api/Employee/";  
  10.   constructor(private http:HttpClient) { }  
  11.    InsertEmployee(employee:Employee)  
  12.    {  
  13.      debugger;  
  14.     const httpOptions = { headers: new HttpHeaders({ 'Content-Type''application/json' }) };  
  15.      return this.http.post<Employee[]>(this.Url+'/InsertEmployee/', employee,httpOptions)  
  16.    }  
  17.    GetEmployeeRecord():Observable<Employee[]>  
  18.    {  
  19.      debugger;  
  20.     return this.http.get<Employee[]>(this.Url+"/GetAllEmployee")  
  21.    }  
  22.    DeleteEmployee(id:string):Observable<number>  
  23.    {  
  24.      debugger;  
  25.     return this.http.get<number>(this.Url + '/Delete/?id='+id);  
  26.    }  
  27.    GetEmployeeById(id:string)  
  28.    {  
  29.     return this.http.get<Employee>(this.Url + '/GetEmployeeById/?id=' + id);  
  30.    }  
  31.    UpdatEmplouee(employee:Employee)  
  32.    {  
  33.     debugger;  
  34.     const httpOptions = { headers: new HttpHeaders({ 'Content-Type''application/json' }) };  
  35.      return this.http.post<Employee[]>(this.Url+'/UpdateEmployee/', employee,httpOptions)  
  36.    }  
  37.   
  38. }  
Step 7 - Add Paging and Searching
 
To add paging and searching, install the following library in the project.
 
For pagination
  1. npm install --save ngx-pagination  
For searching
  1. npm i ng2-search-filter --save  
Export and import both these directives in the app.module.ts file.
  1. import {NgxPaginationModule} from 'ngx-pagination';  
  2. import { Ng2SearchPipeModule } from 'ng2-search-filter';  
Step 8
 
Now, open addemployee.component.html and add the following HTML.
  1. <div class="container" style="padding-top:40px;">    
  2.   <div class="row">    
  3.     <div class="col-md-10 mx-auto">    
  4.       <div class="card mx-4">   
  5.         <div class="card-head p-4">  
  6.             <div class="col-sm-12 btn btn-success">  
  7.                 Employee's Information  
  8.               </div>  
  9.         </div>   
  10.         <div class="card-body p-4">    
  11.      <form [formGroup]="Addemployee" (ngSubmit)="onFormSubmit(Addemployee.value)">  
  12.     <div class="col-sm-12">  
  13.       <div class="card-body">  
  14.         <!-- <div class="row"> -->  
  15.         <div class="form-group ">  
  16.   
  17.           <label class="col-sm-2 control-label" for="Name">Name</label>  
  18.           <div class="col-sm-10">  
  19.             <input type="text" class="form-control" placeholder="Enter name" formControlName="Name">  
  20.           </div>  
  21.         </div>  
  22.         <div class="form-group ">  
  23.           <label class="col-sm-2 control-label" for="Department">Department</label>  
  24.           <div class="col-sm-10">  
  25.             <input type="text" class="form-control" placeholder="Enter Department" formControlName="Department">  
  26.           </div>  
  27.         </div>  
  28.         <div class="form-group ">  
  29.           <label class="col-sm-2 control-label" for="Address">Address</label>  
  30.           <div class="col-sm-10">  
  31.             <input type="text" class="form-control" placeholder="Enter Address" formControlName="Address">  
  32.           </div>  
  33.         </div>  
  34.         <div class="form-group ">  
  35.           <label class="col-sm-2 control-label" for="City">City</label>  
  36.           <div class="col-sm-10">  
  37.             <input type="text" class="form-control" placeholder="Enter City" formControlName="City">  
  38.           </div>  
  39.         </div>  
  40.         <div class="form-group ">  
  41.           <label class="col-sm-2 control-label" for="Country">Country</label>  
  42.           <div class="col-sm-10">  
  43.             <input type="text" class="form-control" placeholder="Enter Country" formControlName="Country">  
  44.           </div>  
  45.         </div>  
  46.   
  47.       </div>  
  48.     </div>  
  49.     <div class="col-6 text-right">    
  50.         <button class="btn btn-primary px-10" type="submit">Add </button>  
  51.       </div>  
  52.   </form>  
  53.       </div>    
  54.     </div>    
  55.   </div>    
  56.   </div>   
  57. </div>   
Step 9
 
Open the addemployee.componet.ts file and add the following lines.
  1. import { Component, OnInit } from '@angular/core';  
  2. import { HttpClient } from "@angular/common/http";  
  3. import { FormGroup, FormControl } from '@angular/forms';  
  4. import { EmprecordService } from "../../emprecord.service";  
  5. import { Employee } from "../../employee";  
  6. import { Observable } from "rxjs";  
  7. import { identifierModuleUrl } from '@angular/compiler';  
  8. import { Router } from '@angular/router';  
  9. @Component({  
  10.   selector: 'app-addemployee',  
  11.   templateUrl: './addemployee.component.html',  
  12.   styleUrls: ['./addemployee.component.css']  
  13. })  
  14. export class AddemployeeComponent implements OnInit {  
  15.   massage: string;  
  16.   dataSaved = false;  
  17.   Addemployee:FormGroup;  
  18.   EmployeeIdUpdate = "0";  
  19.   constructor(private router: Router,private emprecordService:EmprecordService) { }  
  20.   
  21.   InsertEmployee(employee:Employee)  
  22.   {  
  23. debugger;  
  24.     if (this.EmployeeIdUpdate != "0") employee.Id=this.EmployeeIdUpdate;  
  25.       this.emprecordService.InsertEmployee(employee).subscribe(  
  26.         ()=>  
  27.         {  
  28.           if (this.EmployeeIdUpdate == "0") {  
  29.             this.massage = 'Saved Successfully';  
  30.     
  31.           }  
  32.           else  
  33.           {  
  34.             this.massage = 'Update Successfully';  
  35.           }  
  36.           this.dataSaved = true;  
  37.           this.router.navigate(['/employee']);  
  38.         })  
  39.   }  
  40.   onFormSubmit() {  
  41.     const Emp = this.Addemployee.value;  
  42.     this.InsertEmployee(Emp);  
  43.   }  
  44.     
  45.   EmployeeEdit(id: string) {  
  46.     debugger;  
  47.     this.emprecordService.GetEmployeeById(id).subscribe(emp => {  
  48.       this.massage = null;  
  49.       this.dataSaved = false;  
  50.       debugger;  
  51.       this.EmployeeIdUpdate=id;  
  52.       this.Addemployee.controls['Name'].setValue(emp.Name);  
  53.       this.Addemployee.controls['Department'].setValue(emp.Department);  
  54.       this.Addemployee.controls['City'].setValue(emp.City);  
  55.       this.Addemployee.controls['Country'].setValue(emp.Country);  
  56.       this.Addemployee.controls['Address'].setValue(emp.Address);  
  57.     });  
  58.     debugger;  
  59.   }  
  60.   clearform() {  
  61.     debugger;  
  62.     this.Addemployee.controls['Name'].setValue("");  
  63.     this.Addemployee.controls['Department'].setValue("");  
  64.     this.Addemployee.controls['Address'].setValue("");  
  65.     this.Addemployee.controls['City'].setValue("");  
  66.     this.Addemployee.controls['Country'].setValue("");  
  67.      
  68.   }  
  69.   ngOnInit() {  
  70.     this.Addemployee = new FormGroup({  
  71.          
  72.       Name: new FormControl(),  
  73.       Department:new FormControl(),  
  74.       Address:new FormControl(),  
  75.       City:new FormControl(),  
  76.       Country:new FormControl(),  
  77.   });  
  78.   let Id = localStorage.getItem("id");  
  79. if(Id!=null)  
  80. {  
  81.   this.EmployeeEdit(Id) ;  
  82.  }}  
  83. }  
Step 10
 
Open employee.componet.html and add this HTML. 
  1. <div class="container" style="margin-bottom:20px;padding-top:20px;">  
  2.   <div class="row">  
  3.     <div class="col-sm-12 btn btn-success">  
  4.       Employee's Information  
  5.     </div>  
  6.   </div>  
  7.   <div class="col-sm-12" style="margin-bottom:20px;padding-top:20px;">  
  8.     <div class="row">  
  9.       <div class="col-sm-6">  
  10.         <button type="button" class="btn btn-primary" data-toggle="modal" routerLink="/addemployee">  
  11.           Add New Employee  
  12.         </button>  
  13.       </div>  
  14.       <div class="col-sm-6">  
  15.         <input class="form-control" type="text" name="search" [(ngModel)]="filter" placeholder="Search">  
  16.       </div>  
  17.     </div>  
  18.   </div>  
  19. </div>  
  20. <div class="container" style="padding-top:20px;">  
  21.   <table class="table table-striped">  
  22.     <thead class="thead-dark">  
  23.       <th>Name</th>  
  24.       <th>Department</th>  
  25.       <th>Address</th>  
  26.       <th>City</th>  
  27.       <th>Country</th>  
  28.       <th>Action</th>  
  29.     </thead>  
  30.     <tbody>  
  31.       <tr *ngFor="let e of emp | async|filter:filter| paginate: { itemsPerPage: 5, currentPage: p } ; let i=index">  
  32.         <td>{{e.Name}}</td>  
  33.         <td>{{e.Department}}</td>  
  34.         <td>{{e.Address}}</td>  
  35.         <td>{{e.City}}</td>  
  36.         <td>{{e.Country}}</td>  
  37.         <td>  
  38.           <div class="btn-group">  
  39.             <button type="button" class="btn btn-primary mr-1" (click)="EmployeeEdit(e.Id)">Edit</button>  
  40.             <button type="button" class="btn btn-danger mr-1" (click)="Deleteemployee(e.Id)">Delete</button>  
  41.           </div>  
  42.         </td>  
  43.       </tr>  
  44.     </tbody>  
  45.   </table>  
  46.   <ul class="pagination">  
  47.     <pagination-controls (pageChange)="p = $event"></pagination-controls>  
  48.   </ul>  
  49. </div>  
Step 11
 
Open employee.componet.ts file and add the following lines.
  1. import { Component, OnInit } from '@angular/core';  
  2. import { Employee } from "../employee";  
  3. import { EmprecordService } from "../emprecord.service";  
  4. import { Observable } from "rxjs";  
  5. import { Router } from '@angular/router';  
  6. @Component({  
  7.   selector: 'app-employee',  
  8.   templateUrl: './employee.component.html',  
  9.   styleUrls: ['./employee.component.css']  
  10. })  
  11. export class EmployeeComponent implements OnInit {  
  12.   private emp: Observable<Employee[]>;  
  13.   massage:String;  
  14.   dataSaved=false;  
  15.   constructor(private router: Router,private emprecordService:EmprecordService) { }  
  16.    Loademployee()  
  17.    {  
  18.       debugger;  
  19.       this.emp = this.emprecordService.GetEmployeeRecord();  
  20.       console.log(this.emp);  
  21.         
  22.       debugger;  
  23.       
  24.    }  
  25.    EmployeeEdit(id: string) {  
  26.     debugger;  
  27.    localStorage.removeItem("id");  
  28.    localStorage.setItem("id",id.toString());  
  29.     this.router.navigate(['/addemployee'], { queryParams: { Id: id } });  
  30.     debugger;  
  31.   }  
  32.    Deleteemployee(id: string) {  
  33.     if (confirm("Are You Sure To Delete this Informations")) {  
  34.   
  35.       this.emprecordService.DeleteEmployee(id).subscribe(  
  36.         () => {  
  37.           this.dataSaved = true;  
  38.           this.massage = "Deleted Successfully";  
  39.         }  
  40.       );  
  41.     }  
  42.   }  
  43.   ngOnInit() {  
  44.     localStorage.clear();
  45.     this.Loademployee();  
  46.       
  47.   }  
  48.   
  49. }  
Step 12
 
Now, open app-routing.module.ts file and add the following lines to create routing.
  1. import { NgModule } from '@angular/core';  
  2. import { Routes, RouterModule } from '@angular/router';  
  3. import { EmployeeComponent } from "./employee/employee.component";  
  4. import { AddemployeeComponent } from "./employee/addemployee/addemployee.component";  
  5.   
  6. const routes: Routes = [  
  7.  {path:"employee",component:EmployeeComponent},  
  8.  {path:"addemployee",component:AddemployeeComponent},  
  9. ];  
  10.   
  11. @NgModule({  
  12.   imports: [RouterModule.forRoot(routes)],  
  13.   exports: [RouterModule]  
  14. })  
  15. export class AppRoutingModule { }  
Step 13
 
Now, open app.module.ts file and add the following lines,
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { FormsModule } from '@angular/forms';  
  4. import { AppRoutingModule } from './app-routing.module';  
  5. import { AppComponent } from './app.component';  
  6. import { HttpClientModule,HttpClient} from '@angular/common/http';   
  7. import { EmployeeComponent } from './employee/employee.component';  
  8. import { ReactiveFormsModule } from "@angular/forms";  
  9. import { EmprecordService } from "../app/emprecord.service";  
  10. import { AddemployeeComponent } from './employee/addemployee/addemployee.component';   
  11. import {NgxPaginationModule} from 'ngx-pagination';   
  12. import { Ng2SearchPipeModule } from 'ng2-search-filter';  
  13.   
  14. @NgModule({  
  15.   declarations: [  
  16.     AppComponent,  
  17.     EmployeeComponent,  
  18.     AddemployeeComponent,  
  19.   ],  
  20.   imports: [  
  21.     BrowserModule,FormsModule,  
  22.     AppRoutingModule,HttpClientModule,ReactiveFormsModule,Ng2SearchPipeModule,NgxPaginationModule  
  23.   ],  
  24.   providers: [EmprecordService],  
  25.   bootstrap: [AppComponent]  
  26. })  
  27. export class AppModule { }  
Step 14
 
Now, let us run the project and redirect the URL to the "Addemployee" page.
 
CRUD Operations Using Web API, MongoDB And Angular 7
 
Step 15
 
Enter the details and click on the "Add " button.
 
CRUD Operations Using Web API, MongoDB And Angular 7
 

Summary

 
In this article, we discussed how to perform CRUD operations using MongoDB, Angular 7, and Web API.


Similar Articles