Learn ASP.NET Core WEB API With Angular 5 Using ngFor

Introduction

In this article, we will learn ASP.NET Core web API with Angular 5 data binding using with ngFor.

  • Create SQL Server Database
  • Create Web API with ASP.NET Core
  • Install Entity Framework
  • Create angular 5 Application
  • Data Binding Using with ngFor

Create SQL Server Database

Open your SQL Server, click New Query window & run the below SQL script. It will create a new table; insert some data.

  1. USE [master]  
  2. GO  
  3. CREATE DATABASE [DBFirst]    
  4. USE [DBFirst]  
  5. CREATE TABLE [dbo].[EmpMaster](  
  6.     [Row_id] [numeric](18, 0) IDENTITY(1,1) NOT NULL,  
  7.     [Emp_Code] [varchar](10) NULL,  
  8.     [Emp_FName] [varchar](50) NULL,  
  9.     [Emp_LName] [varchar](50) NULL,  
  10.     [Emp_Status] [bitNULL,  
  11.     [Emp_DOB] [datetime] NULL,  
  12.     [Emp_Maritalstatus] [varchar](10) NULL,  
  13.     [Emp_Role] [varchar](50) NULL,  
  14.     [Emp_Department] [varchar](50) NULL,  
  15.     [Emp_Address] [varchar](500) NULL,  
  16.     [Emp_Profilestatus] [intNULL,  
  17.     [Emp_Expriance] [intNULL,  
  18.     [Create_By] [varchar](50) NULL,  
  19.     [Create_Date] [datetime] NULL,  
  20.  CONSTRAINT [PK_EmpMaster] PRIMARY KEY CLUSTERED   
  21. (  
  22.     [Row_id] ASC  
  23. )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ONON [PRIMARY]  
  24. ON [PRIMARY]  
  25. GO  
  26. SET ANSI_PADDING OFF  
  27. GO  
  28. SET IDENTITY_INSERT [dbo].[EmpMaster] ON  
  29. INSERT [dbo].[EmpMaster] ([Row_id], [Emp_Code], [Emp_FName], [Emp_LName], [Emp_Status], [Emp_DOB], [Emp_Maritalstatus], [Emp_Role], [Emp_Department], [Emp_Address], [Emp_Profilestatus], [Emp_Expriance], [Create_By], [Create_Date]) VALUES (CAST(1 AS Numeric(18, 0)), N'1000', N'Amit ', N'Sharma', 1, CAST(0x0000532D00000000 AS DateTime), N'Married', N'Admin', N'Dev', N'California', 100, 20, N'Thiru'CAST(0x0000A7BA00000000 AS DateTime))  
  30. INSERT [dbo].[EmpMaster] ([Row_id], [Emp_Code], [Emp_FName], [Emp_LName], [Emp_Status], [Emp_DOB], [Emp_Maritalstatus], [Emp_Role], [Emp_Department], [Emp_Address], [Emp_Profilestatus], [Emp_Expriance], [Create_By], [Create_Date]) VALUES (CAST(2 AS Numeric(18, 0)), N'2000', N'Erik ', N'Dietrich', 0, CAST(0x00007E0F00000000 AS DateTime), N'Married', N'Employee', N'Dev', N'Washington', 50, 10, N'Thiru'CAST(0x0000A7BA00000000 AS DateTime))  
  31. SET IDENTITY_INSERT [dbo].[EmpMaster] OFF  
  32. /****** Object:  StoredProcedure [dbo].[PC_EmpMaster]    Script Date: 01/21/2018 20:28:16 ******/  
  33. SET ANSI_NULLS ON  
  34. GO  
  35. SET QUOTED_IDENTIFIER ON  
  36. GO  

Create Web API with ASP.NET Core

Open Visual Studio 2017.

ASP.NET Core

Go to New menu > click New & Project. Now, it will open the "New Project" window.

ASP.NET Core

You can select ASP.NET Core Web Application. Enter the name of project in “Solution name” textbox then click OK button.

ASP.NET Core

One more window will appear. Select .NET Core with ASP.NET Core 2.0 Web API in this popup and click OK button.

ASP.NET Core

Some list will be opened in the Solution Explorer.

Install Entity Framework

Run the below commands in NuGet Package Manager > Package Manager Console. It will be using some Entity Framework tools to create a model from the Database and ASP.NET Core Scaffolding tools to create a Controllers and Views.

  • Install-Package Microsoft.EntityFrameworkCore.SqlServer 
  • Install-Package Microsoft.EntityFrameworkCore.Tools
  • Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design

Now, we want to create the Entity Framework model based on our created database. So run this command in Package Manager Console.

Scaffold-DbContext "Server=MYLTOP;Database=DBFirst;User ID=sa;Password=XXX;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Once you are finished with the console, Model will be created like the below screen.
ASP.NET Core

Now, Services are automatically registered with Dependency Injection on application startup. You want to remove the inline context configuration from DBFirstContext.cs.

  1. protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
  2.         {  
  3.          if (!optionsBuilder.IsConfigured)  
  4.          {  
  5. optionsBuilder.UseSqlServer(@"Server=MYLTOP;Database=DBFirst;UserID=sa;Password=XXX;");  
  6.          }  
  7.         }  

Add the below Constrictor line for it will allow configuration to be passed into the context Dependency Injection.

  1. public DBFirstContext(DbContextOptions<DBFirstContext> options)  
  2.    : base(options)  
  3.      { }  

Then, we will register this service in startup.cs. So, the following Header and Services code to be added to the existing lines.

  1. using DotNetCoreAPI.Models;  
  2. using Microsoft.EntityFrameworkCore;  

We want to change the Origin URL allowed to access. So that replaces the following methods in the startup.cs file. Because we can avoid “Access-Control-Allow-Origin” issue

  1. public void ConfigureServices(IServiceCollection services)  
  2.         {  
  3.             services.AddMvc();  
  4.             services.AddCors(options =>  
  5.             {  
  6.                 options.AddPolicy("AllowAll", p =>  
  7.                 {  
  8.                     p.AllowAnyOrigin()  
  9.                     .AllowAnyHeader()  
  10.                     .AllowAnyMethod();  
  11.                 });  
  12.             });  
  13.   
  14.             var connection = @"Server=MYLTOP;Database=DBFirst;User ID=sa;Password=XXX;";  
  15.             services.AddDbContext<DBFirstContext>(options => options.UseSqlServer(connection));  
  16.         }  
  17.   
  18.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  19.         public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
  20.         {  
  21.             if (env.IsDevelopment())  
  22.             {  
  23.                 app.UseDeveloperExceptionPage();  
  24.             }  
  25.   
  26.             app.UseCors("AllowAll");  
  27.             app.UseMvc();  
  28.         }  

Right click on Contollers > Add New Controller > Select API Controller with actions, using Entity Framework

ASP.NET Core

Once Click to Add Button, one more popup will open and it will load the all the Table model on model class & all Database Context will be loaded in the Data context class. If you need to change the controller name:

ASP.NET Core

Now, run the application (Click IIS Express (Play)) & ASP.NET Core Web API has been read for any of the application. We are going to use Angular application.

Create angular 5 Application

Open the Visual Studio Code. If you want to install VS Code, click here. Then, make sure that you have installed node.js or else click here.

Go to Terminal & run the below line for installing Angular CLI.

  • npm install -g @angular/cli@latest
  • ng new UsingCoreAPI
  • cd path\UsingCoreAPI

It will take a few minutes for setup installation. Once it is complete, we will import Angular Service Module in app.component.js and access the ASP.NET Core Web API using HTTP Get function.

  1. import { Component, OnInit } from '@angular/core';  
  2. import { HttpClient } from '@angular/common/http';  
  3. @Component({  
  4.   selector: 'app-root',  
  5.   templateUrl: './app.component.html',  
  6.   styleUrls: ['./app.component.css']  
  7. })  
  8. export class AppComponent implements OnInit {  
  9.   title = 'Angular 5 Using ASP.NET MVC Core API';  
  10.   getEmpData: any = [];  
  11.   constructor(private http: HttpClient) {}  
  12.   
  13.   ngOnInit() {  
  14.     this.http.get('http://localhost:54401/api/EmpMasters')  
  15.     .subscribe (  
  16.       (data) => { this.getEmpData = data;  
  17.       });  
  18.   }  
  19. }  

Change the complier options to be false in tsconfig.json file.

  1. "compilerOptions": {  
  2.     "noImplicitAny"false  
  3. }  

We can test our Web API over the Google ARC Tools & some data has been returned.

ASP.NET Core

 This JSON Data will load to the HTML page using Angular *ngFor.

  1. <table class="table">  
  2. <thead>  
  3.   <tr>  
  4.     <td>Employee Codetd>  
  5.     <td> Nametd>  
  6.    <td>Departmenttd>  
  7.   <td>Locationtd>  
  8.   </tr> </thead>  
  9. <tbody>  
  10.   <tr *ngFor="let emp of getEmpData">  
  11.     <td>{{emp?.empCode}}</td>  
  12.     <td>{{emp?.empFname}}  {{emp?.empLname}}</td>  
  13.     <td>{{emp?.empDepartment}}td>  
  14.     <td>{{emp?.empAddress}}td></tr></tbody>table>  

Run the ng serve command in the VS Code terminal. After executing this line, open your browser on http://localhost:4200/

ASP.NET Core

Conclusion

In this article, we have learned ASP.NET Core Web API with Angular 5 data binding using ngFor. If you have any queries, please tell me through the comments section because your comments are valuable.

Happy Coding!...