Getting Started With HTTP Client Get Request In Angular 8 Using Entity Framework

Introduction

 
In this article, I am going to consume RESfFul API in Angular 8 using the HttpClient module Get request using the entity framework. The HttpClient module is used to GET, POST, PUT, PATCH, and DELETE requests. An Angular application can communicate with backend services over HTTP.
 
Angular HTTP has RxJs observable based API. If Http request fails then Observable emits the error.
 
Note
I am not going to cover the CRUD operation here. This article is to help beginners understand.
 
Prerequisites:
 
We need to install the below software on our laptop/computer,
  • Visual Studio
  • Visual Studio Code
  • Install Node.js & Latest Angular CLI
  • RDBMS Database
Step 1 - Create tables in the database
 
Consider the simple example of employees in a hotel. We will show the name & email ID of the employee in a hotel on the view in the last step of this article.
 
I am going to create one database & will add the table with some values. Use the below script for more information. Note that you can create a database structure as per your requirement.
  1. GO  
  2. SET ANSI_NULLS ON  
  3. GO  
  4. SET QUOTED_IDENTIFIER ON  
  5. GO  
  6. SET ANSI_PADDING ON  
  7. GO  
  8. CREATE TABLE [dbo].[Employee](  
  9.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  10.     [Name] [varchar](100) NULL,  
  11.     [Email] [varchar](50) NULL,  
  12.     [Password] [varchar](50) NULL,  
  13.  CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED   
  14. (  
  15.     [Id] ASC  
  16. )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ONON [PRIMARY]  
  17. ON [PRIMARY]  
  18. GO  
  19. SET ANSI_PADDING OFF  
  20. GO  
  21. SET IDENTITY_INSERT [dbo].[Employee] ON  
  22. INSERT [dbo].[Employee] ([Id], [Name], [Email], [Password]) VALUES (1, N'Rupesh', N'rupesh@yopmail.com', N'123')  
  23. INSERT [dbo].[Employee] ([Id], [Name], [Email], [Password]) VALUES (2, N'Ashish', N'Ashish@yopmail.com', N'123')  
  24. INSERT [dbo].[Employee] ([Id], [Name], [Email], [Password]) VALUES (3, N'Sam', N'Sam@yopmail.com', N'123')  
  25. INSERT [dbo].[Employee] ([Id], [Name], [Email], [Password]) VALUES (4, N'Ajit', N'Ajit@gmail.com', N'123')  
  26. SET IDENTITY_INSERT [dbo].[Employee] OFF  
Step 2 - Create Web API
 
First, we will create a WebAPI application using Visual studio. Open Visual Studio, go to file => New => Project. Go to a new project & create ASP.NET + WebAPI empty project by selecting from the template & give a name to it.
 
Create the .edmx (entity data model) file in our project by right-clicking on the solution => Add => New Item => select ADO.NET Entity Data Model from the installed template of Visual C# in Data. Give a name to it.
 
Getting Started With HTTP Client Get Request In Angular 8 Using Entity Framework
 
Create a web API controller by using the Entity framework. Use the Web API controller with REST actions to perform a CRUD operation from the entity framework context. 
 
Getting Started With HTTP Client Get Request In Angular 8 Using Entity Framework
 
Give a name to our controller. Select a context class name from the drop-down.
 
Getting Started With HTTP Client Get Request In Angular 8 Using Entity Framework
 
We need to add enable the CORS attribute on the above the controller level as per the below syntax. CORS stands for Cross-Origin Resource Sharing.  For more information refer to this article.
  1. [EnableCors(origins: "*", headers: "*", methods: "*")]  
  2. public class EmployeesController : ApiController  
  3. {  
  4. // our CRUD opration code here  
  5. }  
The whole controller code is as shown below:
  1. [EnableCors(origins: "*", headers: "*", methods: "*")]  
  2.     public class EmployeesController : ApiController  
  3.     {  
  4.         private HotelEntities db = new HotelEntities();  
  5.   
  6.         // GET: api/Employees  
  7.         public List<Employee> GetAllEmployees()  
  8.         {  
  9.             return db.Employees.ToList();  
  10.         }  
  11.   
  12.         // GET: api/Employees/5  
  13.         [ResponseType(typeof(Employee))]  
  14.         public IHttpActionResult GetEmployee(int id)  
  15.         {  
  16.             Employee employee = db.Employees.Find(id);  
  17.             if (employee == null)  
  18.             {  
  19.                 return NotFound();  
  20.             }  
  21.   
  22.             return Ok(employee);  
  23.         }  
  24.   
  25.         // PUT: api/Employees/5  
  26.         [ResponseType(typeof(void))]  
  27.         public IHttpActionResult PutEmployee(int id, Employee employee)  
  28.         {  
  29.             if (!ModelState.IsValid)  
  30.             {  
  31.                 return BadRequest(ModelState);  
  32.             }  
  33.   
  34.             if (id != employee.Id)  
  35.             {  
  36.                 return BadRequest();  
  37.             }  
  38.   
  39.             db.Entry(employee).State = EntityState.Modified;  
  40.   
  41.             try  
  42.             {  
  43.                 db.SaveChanges();  
  44.             }  
  45.             catch (DbUpdateConcurrencyException)  
  46.             {  
  47.                 if (!EmployeeExists(id))  
  48.                 {  
  49.                     return NotFound();  
  50.                 }  
  51.                 else  
  52.                 {  
  53.                     throw;  
  54.                 }  
  55.             }  
  56.   
  57.             return StatusCode(HttpStatusCode.NoContent);  
  58.         }  
  59.   
  60.         // POST: api/Employees  
  61.         [ResponseType(typeof(Employee))]  
  62.         public IHttpActionResult PostEmployee(Employee employee)  
  63.         {  
  64.             if (!ModelState.IsValid)  
  65.             {  
  66.                 return BadRequest(ModelState);  
  67.             }  
  68.   
  69.             db.Employees.Add(employee);  
  70.             db.SaveChanges();  
  71.   
  72.             return CreatedAtRoute("DefaultApi"new { id = employee.Id }, employee);  
  73.         }  
  74.   
  75.         // DELETE: api/Employees/5  
  76.         [ResponseType(typeof(Employee))]  
  77.         public IHttpActionResult DeleteEmployee(int id)  
  78.         {  
  79.             Employee employee = db.Employees.Find(id);  
  80.             if (employee == null)  
  81.             {  
  82.                 return NotFound();  
  83.             }  
  84.   
  85.             db.Employees.Remove(employee);  
  86.             db.SaveChanges();  
  87.   
  88.             return Ok(employee);  
  89.         }  
  90.   
  91.         protected override void Dispose(bool disposing)  
  92.         {  
  93.             if (disposing)  
  94.             {  
  95.                 db.Dispose();  
  96.             }  
  97.             base.Dispose(disposing);  
  98.         }  
  99.   
  100.         private bool EmployeeExists(int id)  
  101.         {  
  102.             return db.Employees.Count(e => e.Id == id) > 0;  
  103.         }  
  104.     }  
Step 3
 
To create an Angular Project, refer to this article.
 
To create a component & service refer to the below articles.
Create a new service in our Angular application using syntax & create a company service:
  1. ng g service our_service_name
Now we will write code to get the data from our API in the service i.e. company.service.ts file contains below code.
 
Note
Do not use direct URL link in the typescript file anyone can easily hack it. For demo purposes, I have used it.
 
The below code contains file company.service.ts
  1. import { Injectable } from '@angular/core';
  2. import { HttpClient } from '@angular/common/http';
  3. import {Company} from '../Model/company';

  4. @Injectable({
  5. providedIn: 'root'
  6. })
  7. export class CompanyService {
  8. constructor(private http: HttpClient) { }
  9. getData(){
  10. return this.http.get("http://localhost:8012/api/Employees");
  11. }
  12. }
In the above code, CompanyService is a class which contains out getData method that returns a result from API from where we are getting record using GET request, api/Employees (which is written in API project). We can also host our API project & add that URL as well.
 
Step 4
 
Now create a new component in our angular project using syntax & create my-company component.
  1. ng g c componentName  
The below code contains the file my-company.component.html
  1. <p>Angular 8 using Web API !!!</p>    
  2.     
  3. <div>    
  4.   <table class="gridList">    
  5.     <tr>    
  6.       <th>User Names</th>    
  7.       <th>Email</th>    
  8.     </tr>    
  9.     <tr *ngFor="let item of companyList">    
  10.       <td>{{item.Name }}</td>    
  11.       <td>{{item.Email }}</td>    
  12.     </tr>    
  13.   </table>    
  14. </div>     
In the above code we have used ngFor to iterate the loop. companyList is variable in which we will get the data from our services refer below steps. 
 
The below code contains the file my-company.component .ts 
  1. import { BrowserModule, Title } from '@angular/platform-browser';  
  2. import { Component, OnInit,ViewChild } from '@angular/core';   
  3. import{ CompanyService } from '../../service/company.service';  

  4. @Component({  
  5.   selector: 'app-my-company',  
  6.   templateUrl: './my-company.component.html',  
  7.   styleUrls: ['./my-company.component.css']  
  8. })  
  9. export class MyCompanyComponent implements OnInit {  
  10.  
  11.   companyList: any  
  12.   constructor(private companyService: CompanyService) { }  
  13.   
  14.   ngOnInit() {  
  15.   this.getData();    
  16.   }  
  17.   getData(){  
  18.     this.companyService.getData().subscribe(  
  19.       data => {  
  20.         this.companyList = data;  
  21.       }  
  22.     );  
  23.   }  
  24.   }  
In the above code, we have imported the company service. In OnInit method we will declare one variable companyList & will assign the data which is return by our method getData() from service. 
 
Here, subscribe is used to send the list. 
 
Step 4
 
Now, to load our company component, we will add selector in app.component.html file 
  1. <app-my-company><app-my-company>  
Step 5
 
To run the Angular application, use the below syntax
  1. ng serve -o  
Output
 
Getting Started With HTTP Client Get Request In Angular 8 Using Entity Framework
 

Summary

 
In this article, you learned about the HTTP Client Get Request In Angular 8 using the entity framework.