Fetch Data From Database Using ASP.NET Web API In Angular 6

Introduction

In this article, I will explain how to call ASP.NET web API in your Angular project step by step. You need to enable CORS in your web API and fetch data from web API. It is easy to call API in Angular.

Step 1

Open SQL server 2014 of your choice and create a table and insert some records.
  1. CREATE TABLE [dbo].[Employee](  
  2.     [Employee_Id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [First_Name] [nvarchar](50) NULL,  
  4.     [Last_Name] [nvarchar](50) NULL,  
  5.     [Salary] [money] NULL,  
  6.     [Joing_Date] [nvarchar](50) NULL,  
  7.     [Department] [nvarchar](50) NULL,  
  8.  CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED   
  9. (  
  10.     [Employee_Id] ASC  
  11. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
  12. ) ON [PRIMARY]  
  13.   
  14. GO  

Step 2

Open Visual Studio 2017, click on New Project and create an empty web API application project.
 
Screenshot for creating new project 1 
 
Fetch Data From Database Using ASP.NET Web API In Angular 6 

After clicking on New Project, one window will appear. Select Web from the left panel, choose ASP.NET Web Application, give a meaningful name to your project, and then click on OK as shown in the below screenshot.

Screenshot for creating new project 2

Fetch Data From Database Using ASP.NET Web API In Angular 6

After clicking on OK one more window will appear; choose empty, check on empty Web API checkbox then click on OK as shown in the below screenshot.

Screenshot for creating new project 3

Fetch Data From Database Using ASP.NET Web API In Angular 6

After clicking OK, the project will be created with the name of WebAPICRUD_Demo.

Step 3

Add Entity Framework now. For that, right click on Models folder, select Add, then select New Item, then click on it.

Screenshot for adding entity framework 1

Fetch Data From Database Using ASP.NET Web API In Angular 6

After clicking on a New item, you will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model, give it the name MyModel (this name is not mandatory you can give any name) and click on Add.

Screenshot for adding entity framework 2

Fetch Data From Database Using ASP.NET Web API In Angular 6

After you click on "Add a window", the wizard will open, choose EF Designer from the database and click Next.

Screenshot for adding entity framework 3

Fetch Data From Database Using ASP.NET Web API In Angular 6

After clicking on Next a window will appear. Choose New Connection. Another window will appear, add your server name if it is local then enter a dot (.). Choose your database and click on OK.

Screenshot for adding entity framework 4

Fetch Data From Database Using ASP.NET Web API In Angular 6

The connection will be added. If you wish to save connect as you want. You can change the name of your connection below. It will save connection in web config then click on Next.

Screenshot for adding entity framework 5

Fetch Data From Database Using ASP.NET Web API In Angular 6

After clicking on NEXT another window will appear to choose database table name as shown in the below screenshot then click on Finish.

Entity framework will be added and the respective class gets generated under the Models folder.

Screenshot for adding entity framework 6

Fetch Data From Database Using ASP.NET Web API In Angular 6

Following class will be added,

  1. namespace WebAPICURD_Demo.Models  
  2. {  
  3.     using System;  
  4.     using System.Collections.Generic;  
  5.       
  6.     public partial class Employee  
  7.     {  
  8.         public int Employee_Id { get; set; }  
  9.         public string First_Name { get; set; }  
  10.         public string Last_Name { get; set; }  
  11.         public Nullable<decimal> Salary { get; set; }  
  12.         public string Joing_Date { get; set; }  
  13.         public string Department { get; set; }  
  14.     }  
  15. }  

Step 4

Right click on Controllers folder, select Add, then choose Controller as shown in the below screenshot.

Screenshot 1

Fetch Data From Database Using ASP.NET Web API In Angular 6

After clicking on the controller a window will appear to choose Web API 2 Controller-Empty, click on Add.

Fetch Data From Database Using ASP.NET Web API In Angular 6

After clicking on Add, another window will appear with DefaultController. Change the name to EmployeeController then click on Add. EmployeeController will be added under Controllers folder. Remember don’t change the Controller suffix for all controllers, change only highlight, and instead of Default just change Home as shown in the below screenshot.

Fetch Data From Database Using ASP.NET Web API In Angular 6

Complete code for 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 WebAPICURD_Demo.Models;  
  8.   
  9. namespace WebAPICURD_Demo.Controllers  
  10. {  
  11.     public class EmployeeController : ApiController  
  12.     {  
  13.          
  14.         private EmployeeEntities _db;  
  15.         public EmployeeController()  
  16.         {  
  17.             _db =new EmployeeEntities();  
  18.         }  
  19.         public IEnumerable<Employee> GetEmployees()  
  20.         {  
  21.             return _db.Employees.ToList();  
  22.         }  
  23.     }  
  24. }  

Step 5

Now, enable CORS in the WebService app. First, add the CORS NuGet package. In Visual Studio, from the Tools menu, select NuGet Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command.
  1. Install-Package Microsoft.AspNet.WebApi.Cors  

This command installs the latest package and updates all dependencies, including the core Web API libraries.

Step 6

Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method.

Add namespace

  1. using System.Web.Http.Cors;  

Add the following line of code,

  1. EnableCorsAttribute cors = new EnableCorsAttribute("*","*","*");  
  2. config.EnableCors(cors);  

Complete WebApiConfig.cs file code

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web.Http;  
  5. using System.Web.Http.Cors;  
  6.   
  7. namespace WebAPICURD_Demo  
  8. {  
  9.     public static class WebApiConfig  
  10.     {  
  11.         public static void Register(HttpConfiguration config)  
  12.         {  
  13.             // Web API configuration and services  
  14.               
  15.             // Web API routes  
  16.             config.MapHttpAttributeRoutes();  
  17.   
  18.             config.Routes.MapHttpRoute(  
  19.                 name: "DefaultApi",  
  20.                 routeTemplate: "api/{controller}/{id}",  
  21.                 defaults: new { id = RouteParameter.Optional }  
  22.             );  
  23.   
  24.             EnableCorsAttribute cors = new EnableCorsAttribute("*","*","*");  
  25.             config.EnableCors(cors);  
  26.         }  
  27.     }  
  28. }  

Step 6

Open Visual Studio Code and create a new Angular project.
  1. ng new MyDemo  

Compile your project

  1. cd MyDemo  

Open your project in the browser,

  1. ng serve --open  

Step 7

Install bootstrap in your project and import in style.css file,
  1. npm install bootstrap –save  
  1. @import 'node_modules/bootstrap/dist/css/bootstrap.min.css';  

Step 8

Open terminal create component,
  1. ng g c employee-list  

Step 9

Open app.module.ts file and import httpModule
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import {HttpClientModule, HttpClient} from '@angular/common/http';  
  4.   
  5. import { AppComponent } from './app.component';  
  6. import { from } from 'rxjs';  
  7. import { EmployeeListComponent } from './employee-list/employee-list.component';  
  8.   
  9. @NgModule({  
  10.   declarations: [  
  11.     AppComponent,  
  12.     EmployeeListComponent  
  13.   ],  
  14.   imports: [  
  15.     BrowserModule,  
  16.     HttpClientModule  
  17.   ],  
  18.   providers: [],  
  19.   bootstrap: [AppComponent]  
  20. })  
  21. export class AppModule { }  

Step 10

Open employee-list component.ts file and add the following code,
  1. import { HttpClientModule, HttpClient } from '@angular/common/http';  
  2. import { Component, OnInit } from '@angular/core';  
  3.   
  4. @Component({  
  5.   selector: 'app-employee-list',  
  6.   templateUrl: './employee-list.component.html',  
  7.   styleUrls: ['./employee-list.component.css']  
  8. })  
  9. export class EmployeeListComponent implements OnInit {  
  10.   
  11.   constructor(private httpService: HttpClient) { }  
  12.   employees: string[];  
  13.   ngOnInit() {  
  14.     this.httpService.get('http://localhost:52202/api/employee').subscribe(  
  15.       data => {  
  16.        this.employees = data as string [];  
  17.       }  
  18.     );  
  19.   }  
  20.   
  21. }  

Step 11

open employee-list.component.html and add the following code,
  1. <div class="container py-5">  
  2.     <h3 class="text-center text-uppercase">List of Employees</h3>  
  3.     <table class="table table-bordered table-striped">  
  4.         <thead>  
  5.             <tr class="text-center text-uppercase">  
  6.                 <th>Employee ID</th>  
  7.                 <th>First Name</th>  
  8.                 <th>Last Name</th>  
  9.                 <th>Salary</th>  
  10.                 <th>Joining Date</th>  
  11.                 <th>Department</th>  
  12.               </tr>  
  13.         </thead>  
  14.         <tbody>  
  15.           <tr *ngFor="let emp of employees">  
  16.             <td>{{emp.Employee_Id}}</td>  
  17.             <td>{{emp.First_Name}}</td>  
  18.             <td>{{emp.Last_Name}}</td>  
  19.             <td>{{emp.Salary}}</td>  
  20.             <td>{{emp.Joing_Date}}</td>  
  21.             <td>{{emp.Department}}</td>  
  22.           </tr>  
  23.         </tbody>  
  24.       </table>  
  25.     </div>  

Step 12

Add your employee-list.component.html selector in app.component.html
  1. <app-employee-list></app-employee-list>  

Step 13

Run your project in browser.

Output

Fetch Data From Database Using ASP.NET Web API In Angular 6