Retrieve Data From MongoDB Using Web API And Angular 6

In this article we will learn how we fetch data from MongoDB using ASP.NET Web API and bind data using Angular 6. First, we are going to create a web API for retrieving data.

Open Visual Studio and create a new project.
 
Retrieve Data From MongoDB Using Web API And Angular 6 
 
Create a new project and rename it as 'RETDATAAPI'
 
Retrieve Data From MongoDB Using Web API And Angular 6 
 
Choose Web API Template
 
Retrieve Data From MongoDB Using Web API And Angular 6 
 
Now, click on the controller folder and select the Web API 2 controller.
 
Retrieve Data From MongoDB Using Web API And Angular 6 
 
 Rename it as RETDATA
 
Retrieve Data From MongoDB Using Web API And Angular 6 

Step 2

Add MongoDB Drivers for C# using NuGet Package Manager.

Retrieve Data From MongoDB Using Web API And Angular 6
 
Add the required namespaces for MongoDB.
  1. using MongoDB.Driver;  
  2. using MongoDB.Bson;  
Add CORS from NuGet Package Manager.
 
Retrieve Data From MongoDB Using Web API And Angular 6 
 
Now, open Web Apiconfig.cs and add the following lines.
  1. EnableCorsAttribute cors = new EnableCorsAttribute("*""*""*");  
  2. config.EnableCors(cors);  
Complete code
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Net.Http;    
  5. using System.Web.Http;    
  6. using Microsoft.Owin.Security.OAuth;    
  7. using Newtonsoft.Json.Serialization;    
  8. using System.Web.Http.Cors;    
  9.     
  10. namespace RETDATAAPI    
  11. {    
  12.     public static class WebApiConfig    
  13.     {    
  14.         public static void Register(HttpConfiguration config)a    
  15.         {    
  16.             // Web API configuration and services    
  17.             // Configure Web API to use only bearer token authentication.    
  18.             config.SuppressDefaultHostAuthentication();    
  19.             config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));    
  20.     
  21.             // Web API routes    
  22.             config.MapHttpAttributeRoutes();    
  23.     
  24.             config.Routes.MapHttpRoute(    
  25.                 name: "DefaultApi",    
  26.                 routeTemplate: "api/{controller}/{id}",    
  27.                 defaults: new { id = RouteParameter.Optional }    
  28.             );    
  29.             EnableCorsAttribute cors = new EnableCorsAttribute("*""*""*");    
  30.             config.EnableCors(cors);    
  31.         }    
  32.     }    
  33. }   
Now, click on the Model folder and add a new class and rename it as EmployeeDetails and add the following namespace and fields.
  1. using MongoDB.Bson;    
  2. using MongoDB.Bson.Serialization.Attributes;     
  3. public class EmployeeDetails    
  4.    {    
  5.        [BsonId]    
  6.        public ObjectId Id { get; set; }    
  7.        public string Name { get; set; }    
  8.        public string Department { get; set; }    
  9.        public string Address { get; set; }    
  10.        public string City { get; set; }    
  11.        public string Country { get; set; }    
  12.     
  13.    }   
Now, add a method in the controller and add the following code.
  1. public object Getemp()    
  2.         {    
  3.             var Mongodbconnection = "mongodb://localhost";    
  4.             var Client = new MongoClient(Mongodbconnection);    
  5.             var DB = Client.GetDatabase("Employee");    
  6.             var collection = DB.GetCollection<EmployeeDetails>("EmployeeDetails").Find(new BsonDocument()).ToList();    
  7.             return Json(collection);    
  8.         }   
Complete Controller.
  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 RETDATAAPI.Models;    
  10.     
  11. namespace RETDATAAPI.Controllers    
  12. {    
  13.     public class RETDATAController : ApiController    
  14.     {    
  15.         public object Getemp()    
  16.         {    
  17.             var Mongodbconnection = "mongodb://localhost";    
  18.             var Client = new MongoClient(Mongodbconnection);    
  19.             var DB = Client.GetDatabase("Employee");    
  20.             var collection = DB.GetCollection<EmployeeDetails>("EmployeeDetails").Find(new BsonDocument()).ToList();    
  21.             return Json(collection);    
  22.         }    
  23.     }    
  24. }   
Run the Project and check the result of API.
 
Retrieve Data From MongoDB Using Web API And Angular 6 
Now, we want to display this data using Angular 6 into a HTML Table, for this first create a new Angular Project by using Cmd using the command,
 
ng new EmpDetails
 
Retrieve Data From MongoDB Using Web API And Angular 6
 
Open the project in Vs code and add a component by using the command,
 
ng new c Details
 
Retrieve Data From MongoDB Using Web API And Angular 6
 
Add bootstarp in the project to add some styles.

Now open app.module.ts file and import these modules.

  1. import {HttpClientModule, HttpClient} from '@angular/common/http';  
Complete app.module.ts
  1. import { BrowserModule } from '@angular/platform-browser';    
  2. import { NgModule } from '@angular/core';    
  3. import {HttpClientModule, HttpClient} from '@angular/common/http';    
  4. import { AppRoutingModule } from './app-routing.module';    
  5. import { AppComponent } from './app.component';    
  6. import { DetailsComponent } from './details/details.component';    
  7.     
  8. @NgModule({    
  9.   declarations: [    
  10.     AppComponent,    
  11.     DetailsComponent    
  12.   ],    
  13.   imports: [    
  14.     BrowserModule,    
  15.     AppRoutingModule,HttpClientModule    
  16.   ],    
  17.   providers: [],    
  18.   bootstrap: [AppComponent]    
  19. })    
  20. export class AppModule { }   
Now, open Details.component.ts and add the following lines,
  1. import { Component, OnInit } from '@angular/core';    
  2. import {HttpClientModule,HttpClient} from '@angular/common/http';    
  3. @Component({    
  4.   selector: 'app-details',    
  5.   templateUrl: './details.component.html',    
  6.   styleUrls: ['./details.component.css']    
  7. })    
  8. export class DetailsComponent implements OnInit {    
  9.     
  10.   constructor(private httpservice:HttpClient) { }    
  11.   Emp:string[];    
  12.   ngOnInit() {    
  13.     this.httpservice.get('http://localhost:2338/api/RETDATA/Getemp').subscribe(data=>    
  14.       {    
  15.         this.Emp = data as string [];      
  16.       });          
  17.   }      
  18. }   
 Now, open details.component.Html and add the following lines,
  1. <div class="container">    
  2.   <table class="table table-bordered  thead-dark ">      
  3.       <thead class="thead-dark">      
  4.           <tr class="text-center text-uppercase">      
  5.                   
  6.               <th>Name</th>      
  7.               <th>Department</th>      
  8.               <th>Address</th>      
  9.               <th>City</th>      
  10.               <th>Country</th>      
  11.                  
  12.             </tr>      
  13.       </thead>      
  14.       <tbody>      
  15.         <tr class="text-center" *ngFor="let Emp of Emp">      
  16.           
  17.           <td>{{Emp.Name}}</td>      
  18.           <td>{{Emp.Department}}</td>      
  19.           <td>{{Emp.Address}}</td>     
  20.           <td>{{Emp.City}}</td>      
  21.           <td>{{Emp.Country}}</td>             
  22.               
  23.         </tr>      
  24.       </tbody>      
  25.     </table>      
  26. </div>   
Now, run the project by using this command,
 
ng serve -o
 
Retrieve Data From MongoDB Using Web API And Angular 6
 
Summary 
 
In this article, we learned how we fetch data from the database using Web API and display it using Angular 6.