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.
Create a new project and rename it as 'RETDATAAPI'
Choose Web API Template
Now, click on the controller folder and select the Web API 2 controller.
Rename it as RETDATA
Step 2
Add MongoDB Drivers for C# using NuGet Package Manager.
Add the required namespaces for MongoDB.
- using MongoDB.Driver;
- using MongoDB.Bson;
Add CORS from NuGet Package Manager.
Now, open Web Apiconfig.cs and add the following lines.
- EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
- config.EnableCors(cors);
Complete code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net.Http;
- using System.Web.Http;
- using Microsoft.Owin.Security.OAuth;
- using Newtonsoft.Json.Serialization;
- using System.Web.Http.Cors;
-
- namespace RETDATAAPI
- {
- public static class WebApiConfig
- {
- public static void Register(HttpConfiguration config)a
- {
-
-
- config.SuppressDefaultHostAuthentication();
- config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
-
-
- config.MapHttpAttributeRoutes();
-
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
- EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
- config.EnableCors(cors);
- }
- }
- }
Now, click on the Model folder and add a new class and rename it as EmployeeDetails and add the following namespace and fields.
- using MongoDB.Bson;
- using MongoDB.Bson.Serialization.Attributes;
- public class EmployeeDetails
- {
- [BsonId]
- public ObjectId Id { get; set; }
- public string Name { get; set; }
- public string Department { get; set; }
- public string Address { get; set; }
- public string City { get; set; }
- public string Country { get; set; }
-
- }
Now, add a method in the controller and add the following code.
- public object Getemp()
- {
- var Mongodbconnection = "mongodb://localhost";
- var Client = new MongoClient(Mongodbconnection);
- var DB = Client.GetDatabase("Employee");
- var collection = DB.GetCollection<EmployeeDetails>("EmployeeDetails").Find(new BsonDocument()).ToList();
- return Json(collection);
- }
Complete Controller.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using MongoDB.Driver;
- using MongoDB.Bson;
- using RETDATAAPI.Models;
-
- namespace RETDATAAPI.Controllers
- {
- public class RETDATAController : ApiController
- {
- public object Getemp()
- {
- var Mongodbconnection = "mongodb://localhost";
- var Client = new MongoClient(Mongodbconnection);
- var DB = Client.GetDatabase("Employee");
- var collection = DB.GetCollection<EmployeeDetails>("EmployeeDetails").Find(new BsonDocument()).ToList();
- return Json(collection);
- }
- }
- }
Run the Project and check the result of API.
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
Open the project in Vs code and add a component by using the command,
ng new c Details
Add
bootstarp in the project to add some styles.
Now open app.module.ts file and import these modules.
- import {HttpClientModule, HttpClient} from '@angular/common/http';
Complete app.module.ts
- import { BrowserModule } from '@angular/platform-browser';
- import { NgModule } from '@angular/core';
- import {HttpClientModule, HttpClient} from '@angular/common/http';
- import { AppRoutingModule } from './app-routing.module';
- import { AppComponent } from './app.component';
- import { DetailsComponent } from './details/details.component';
-
- @NgModule({
- declarations: [
- AppComponent,
- DetailsComponent
- ],
- imports: [
- BrowserModule,
- AppRoutingModule,HttpClientModule
- ],
- providers: [],
- bootstrap: [AppComponent]
- })
- export class AppModule { }
Now, open Details.component.ts and add the following lines,
- import { Component, OnInit } from '@angular/core';
- import {HttpClientModule,HttpClient} from '@angular/common/http';
- @Component({
- selector: 'app-details',
- templateUrl: './details.component.html',
- styleUrls: ['./details.component.css']
- })
- export class DetailsComponent implements OnInit {
-
- constructor(private httpservice:HttpClient) { }
- Emp:string[];
- ngOnInit() {
- this.httpservice.get('http://localhost:2338/api/RETDATA/Getemp').subscribe(data=>
- {
- this.Emp = data as string [];
- });
- }
- }
Now, open details.component.Html and add the following lines,
- <div class="container">
- <table class="table table-bordered thead-dark ">
- <thead class="thead-dark">
- <tr class="text-center text-uppercase">
-
- <th>Name</th>
- <th>Department</th>
- <th>Address</th>
- <th>City</th>
- <th>Country</th>
-
- </tr>
- </thead>
- <tbody>
- <tr class="text-center" *ngFor="let Emp of Emp">
-
- <td>{{Emp.Name}}</td>
- <td>{{Emp.Department}}</td>
- <td>{{Emp.Address}}</td>
- <td>{{Emp.City}}</td>
- <td>{{Emp.Country}}</td>
-
- </tr>
- </tbody>
- </table>
- </div>
Now, run the project by using this command,
ng serve -o
Summary
In this article, we learned how we fetch data from the database using Web API and display it using Angular 6.