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. namespace RETDATAAPI
  10. {
  11. public static class WebApiConfig
  12. {
  13. public static void Register(HttpConfiguration config)a
  14. {
  15. // Web API configuration and services
  16. // Configure Web API to use only bearer token authentication.
  17. config.SuppressDefaultHostAuthentication();
  18. config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
  19. // Web API routes
  20. config.MapHttpAttributeRoutes();
  21. config.Routes.MapHttpRoute(
  22. name: "DefaultApi",
  23. routeTemplate: "api/{controller}/{id}",
  24. defaults: new { id = RouteParameter.Optional }
  25. );
  26. EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
  27. config.EnableCors(cors);
  28. }
  29. }
  30. }
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. }
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. namespace RETDATAAPI.Controllers
  11. {
  12. public class RETDATAController : ApiController
  13. {
  14. public object Getemp()
  15. {
  16. var Mongodbconnection = "mongodb://localhost";
  17. var Client = new MongoClient(Mongodbconnection);
  18. var DB = Client.GetDatabase("Employee");
  19. var collection = DB.GetCollection<EmployeeDetails>("EmployeeDetails").Find(new BsonDocument()).ToList();
  20. return Json(collection);
  21. }
  22. }
  23. }
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. @NgModule({
  8. declarations: [
  9. AppComponent,
  10. DetailsComponent
  11. ],
  12. imports: [
  13. BrowserModule,
  14. AppRoutingModule,HttpClientModule
  15. ],
  16. providers: [],
  17. bootstrap: [AppComponent]
  18. })
  19. 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. constructor(private httpservice:HttpClient) { }
  10. Emp:string[];
  11. ngOnInit() {
  12. this.httpservice.get('http://localhost:2338/api/RETDATA/Getemp').subscribe(data=>
  13. {
  14. this.Emp = data as string [];
  15. });
  16. }
  17. }
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. <th>Name</th>
  6. <th>Department</th>
  7. <th>Address</th>
  8. <th>City</th>
  9. <th>Country</th>
  10. </tr>
  11. </thead>
  12. <tbody>
  13. <tr class="text-center" *ngFor="let Emp of Emp">
  14. <td>{{Emp.Name}}</td>
  15. <td>{{Emp.Department}}</td>
  16. <td>{{Emp.Address}}</td>
  17. <td>{{Emp.City}}</td>
  18. <td>{{Emp.Country}}</td>
  19. </tr>
  20. </tbody>
  21. </table>
  22. </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.