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.
- USE [master]
- GO
- CREATE DATABASE [DBFirst]
- USE [DBFirst]
- CREATE TABLE [dbo].[EmpMaster](
- [Row_id] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
- [Emp_Code] [varchar](10) NULL,
- [Emp_FName] [varchar](50) NULL,
- [Emp_LName] [varchar](50) NULL,
- [Emp_Status] [bit] NULL,
- [Emp_DOB] [datetime] NULL,
- [Emp_Maritalstatus] [varchar](10) NULL,
- [Emp_Role] [varchar](50) NULL,
- [Emp_Department] [varchar](50) NULL,
- [Emp_Address] [varchar](500) NULL,
- [Emp_Profilestatus] [int] NULL,
- [Emp_Expriance] [int] NULL,
- [Create_By] [varchar](50) NULL,
- [Create_Date] [datetime] NULL,
- CONSTRAINT [PK_EmpMaster] PRIMARY KEY CLUSTERED
- (
- [Row_id] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- GO
- SET ANSI_PADDING OFF
- GO
- SET IDENTITY_INSERT [dbo].[EmpMaster] ON
- 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))
- 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))
- SET IDENTITY_INSERT [dbo].[EmpMaster] OFF
- /****** Object: StoredProcedure [dbo].[PC_EmpMaster] Script Date: 01/21/2018 20:28:16 ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
Create Web API with ASP.NET Core
Open Visual Studio 2017.
Go to New menu > click New & Project. Now, it will open the "New Project" window.
You can select ASP.NET Core Web Application. Enter the name of project in “Solution name” textbox then click OK button.
One more window will appear. Select .NET Core with ASP.NET Core 2.0 Web API in this popup and click OK button.
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.
Now, Services are automatically registered with Dependency Injection on application startup. You want to remove the inline context configuration from DBFirstContext.cs.
- protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
- {
- if (!optionsBuilder.IsConfigured)
- {
- optionsBuilder.UseSqlServer(@"Server=MYLTOP;Database=DBFirst;UserID=sa;Password=XXX;");
- }
- }
Add the below Constrictor line for it will allow configuration to be passed into the context Dependency Injection.
- public DBFirstContext(DbContextOptions<DBFirstContext> options)
- : base(options)
- { }
Then, we will register this service in startup.cs. So, the following Header and Services code to be added to the existing lines.
- using DotNetCoreAPI.Models;
- 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
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddMvc();
- services.AddCors(options =>
- {
- options.AddPolicy("AllowAll", p =>
- {
- p.AllowAnyOrigin()
- .AllowAnyHeader()
- .AllowAnyMethod();
- });
- });
-
- var connection = @"Server=MYLTOP;Database=DBFirst;User ID=sa;Password=XXX;";
- services.AddDbContext<DBFirstContext>(options => options.UseSqlServer(connection));
- }
-
-
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
-
- app.UseCors("AllowAll");
- app.UseMvc();
- }
Right click on Contollers > Add New Controller > Select API Controller with actions, using Entity Framework
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:
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.
- import { Component, OnInit } from '@angular/core';
- import { HttpClient } from '@angular/common/http';
- @Component({
- selector: 'app-root',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.css']
- })
- export class AppComponent implements OnInit {
- title = 'Angular 5 Using ASP.NET MVC Core API';
- getEmpData: any = [];
- constructor(private http: HttpClient) {}
-
- ngOnInit() {
- this.http.get('http://localhost:54401/api/EmpMasters')
- .subscribe (
- (data) => { this.getEmpData = data;
- });
- }
- }
Change the complier options to be false in tsconfig.json file.
- "compilerOptions": {
- "noImplicitAny": false
- }
We can test our Web API over the Google ARC Tools & some data has been returned.
This JSON Data will load to the HTML page using Angular *ngFor.
- <table class="table">
- <thead>
- <tr>
- <td>Employee Codetd>
- <td> Nametd>
- <td>Departmenttd>
- <td>Locationtd>
- </tr> </thead>
- <tbody>
- <tr *ngFor="let emp of getEmpData">
- <td>{{emp?.empCode}}</td>
- <td>{{emp?.empFname}} {{emp?.empLname}}</td>
- <td>{{emp?.empDepartment}}td>
- <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/
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!...