Angular 8 - CRUD Operations - Part Two

This is the continues of Angular 8 - CRUD Operations - Part One. In this article, we will learn about Angular Routing and Angular Services and How to make a Web API with entity framework using NORTHWND SQL Server database.
 

Angular Routing

 
The Angular Router is used to navigate between views or pages that are triggered by the user's actions. The navigation or view changes happen when the user clicks on the link, click on the button, or enters the URL from the browser address bar.
 
In this sample, I am converting my website which was built in AngularJS into Angular 8. So, navigations are according to my website need.
 
First you need to create a few components using CLI command,
 
ng generate component blog
ng generate component article
 
Now go to app-routing.module.ts file and add the component references and redirect routing.
  1. import { NgModule } from '@angular/core';  
  2. import { Routes, RouterModule } from '@angular/router';  
  3. import { EmployeeComponent } from './employee/employee.component'  
  4. import { AboutComponent } from './about/about.component'  
  5. import { ContactComponent } from './contact/contact.component'  
  6. import { BlogComponent } from './blog/blog.component'  
  7. import { ArticleComponent } from './article/article.component'  
  8. import { CodingComponent } from './coding/coding.component'  
  9. import { SnippetComponent } from './snippet/snippet.component'  
  10. import { PageNotFoundComponent } from './page-not-found/page-not-found.component';  
  11.   
  12. const routes: Routes = [  
  13.   {path: 'employee', component: EmployeeComponent},  
  14.   {path: 'about', component: AboutComponent},  
  15.   {path: 'contact', component: ContactComponent},  
  16.   {path: 'blog', component: BlogComponent},  
  17.   {path: 'article', component: ArticleComponent},  
  18.   {path: 'coding', component: CodingComponent},  
  19.   {path: 'snippet', component: SnippetComponent},  
  20.   { path: '',   redirectTo: '/home', pathMatch: 'full' },  
  21.   { path: '**', component: PageNotFoundComponent }  
  22. ];  
  23.   
  24. @NgModule({  
  25.   imports: [RouterModule.forRoot(routes)],  
  26.   exports: [RouterModule]  
  27. })  
  28. export class AppRoutingModule { }  
Add a new navbar component and add the following code,
  1. <nav class="navbar navbar-expand-lg navbar-dark bg-dark">  
  2.   <a class="navbar-brand logo" href="#">DotNetBuild</a>  
  3.   <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">  
  4.     <span class="navbar-toggler-icon"></span>  
  5.   </button>  
  6.   
  7.   <div class="collapse navbar-collapse"  [ngClass]="{ 'show': navbarOpen }" id="navbarSupportedContent">  
  8.     <ul class="navbar-nav mr-auto">  
  9.       <li class="nav-item active">  
  10.         <a class="nav-link" routerLink="" routerLinkActive="active">Home <span class="sr-only">(current)</span></a>  
  11.       </li>  
  12.       <li class="nav-item">  
  13.         <a class="nav-link" routerLink="/employee" routerLinkActive="active">Employee</a>  
  14.       </li>  
  15.       <li class="nav-item">  
  16.         <a class="nav-link" routerLink="/blog" routerLinkActive="active">Blogs</a>  
  17.       </li>  
  18.       <li class="nav-item">  
  19.         <a class="nav-link" routerLink="/article" routerLinkActive="active">Articles</a>  
  20.       </li>  
  21.       <li class="nav-item">  
  22.         <a class="nav-link" routerLink="/coding" routerLinkActive="active">Coding Tips</a>  
  23.       </li>  
  24.       <li class="nav-item">  
  25.         <a class="nav-link" routerLink="/snippet" routerLinkActive="active">Code Snippet</a>  
  26.       </li>  
  27.       <li class="nav-item">  
  28.         <a class="nav-link" routerLink="/about" routerLinkActive="active">About Us</a>  
  29.       </li>  
  30.       <li class="nav-item">  
  31.         <a class="nav-link" routerLink="/contact" routerLinkActive="active">Contact Us</a>  
  32.       </li>  
  33.     </ul>  
  34.     <ul class="navbar-nav ">  
  35.       <li class="nav-item">  
  36.         <a class="nav-link" href="#"><fa-icon [icon]='faSearch'></fa-icon></a>  
  37.       </li>  
  38.       <li class="nav-item">  
  39.         <a class="nav-link" href="#"><fa-icon [icon]='faBell'></fa-icon></a>  
  40.       </li>  
  41.       <li class="nav-item">  
  42.         <a class="nav-link" href="#"><fa-icon [icon]='faUser'></fa-icon></a>  
  43.       </li>  
  44.       <li class="nav-item dropdown">  
  45.         <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true"  
  46.         aria-expanded="false">User1</a>  
  47.         <div class="dropdown-menu">  
  48.           <a class="dropdown-item" href="#">User2</a>  
  49.           <a class="dropdown-item" href="#">User3</a>  
  50.           <a class="dropdown-item" href="#">Kids</a>  
  51.         </div>  
  52.       </li>  
  53.     </ul>  
  54.   </div>  
  55. </nav>  
Go to app.component.html and navbar component and router-outlet and app-footer.
  1. <div>  
  2.     <app-navbar></app-navbar>  
  3. </div>  
  4. <div class="container">  
  5.     <router-outlet></router-outlet>  
  6. </div>  
  7. <div>  
  8.     <app-footer></app-footer>  
  9. </div>  
In the given html, I have used Bootstrap, Font awesome and AngularJS Material.
 
Let's add the following styles and java scripts into the application before going further.
 
Go to Terminal and install the following,
 
npm install bootstrap –-save
npm install jquery –save
npm install --save @angular/material
npm install font-awesome --save
 
Once you have installed everything then you will find these files in your node module folder,
 
node_modules/jquery/dist/jquery.min.js
node_modules/bootstrap/dist/css/bootstrap.min.css
node_modules/bootstrap/dist/js/bootstrap.min.js
 
Then you have to update your angular.json file,
  1. "styles": [  
  2.              "src/styles.scss",  
  3.              "node_modules/bootstrap/dist/css/bootstrap.min.css"  
  4.            ],  
  5.            "scripts": [  
  6.              "node_modules/jquery/dist/jquery.min.js",  
  7.              "node_modules/bootstrap/dist/js/bootstrap.min.js"  
  8.            ]  
Run the application to see the output,
 
Provide the following command to run.
 
Angular 8 - CRUD Operations
 
Give http://localhost:4200/ in browser.
 
Angular 8 - CRUD Operations
 
If you click on any menu, every menu will redirect to the provided endpoint.
 
Angular 8 - CRUD Operations
 
We are done here with the routing part, now let's build a Web API with Entity framework and SQL Server database.
 

Web API

 
The ASP.NET Web API is an extensible framework for creating HTTP based services that can be accessed in different applications on different platforms such as web, windows, mobile etc. It works the same way as ASP.NET MVC web applications do,  except that it sends data as a response instead of html view. It supports HTTP protocol only.
 
Let’s create a Web API using Visual Studio 2019.
  • Start Visual Studio 2019
  • Create a New WEB Projects and Select Web API
  • Give a name and browse location
  • Click OK
Once the project is created, right click on Models and click on Add >> Add New Item and select ADO.NET Entity Data Model from installed Data templates. Follow these steps,
  • Provide name of model
  • Choose EF designer from database model contents and click next
  • Choose you data connection, make new if not available
  • Provide server name and select database from list
  • Test connection and click next
  • Select entity framework version
  • Choose database tables and give model namespace and click finish
Database diagram
 
Angular 8 - CRUD Operations
 
Web API structure
 
Angular 8 - CRUD Operations
 
Add a new API controller in Controller folder and CRUD functions.
  1. using northwnd_employee_api.Models;  
  2. using System;  
  3. using System.Linq;  
  4. using System.Web.Http;  
  5.   
  6. namespace northwnd_employee_api.Controllers  
  7. {  
  8.     [RoutePrefix("Api/Employee")]  
  9.     public class EmployeeController : ApiController  
  10.     {  
  11.         // GET api/<controller>  
  12.         NorthwindEntities objEntity = new NorthwindEntities();  
  13.         [HttpGet]  
  14.         [Route("GetEmployees")]  
  15.         public IQueryable<Employee> GetEmployees()  
  16.         {  
  17.             try  
  18.             {  
  19.                 return objEntity.Employees;  
  20.             }  
  21.             catch (Exception)  
  22.             {  
  23.                 throw;  
  24.             }  
  25.         }  
  26.         // GET api/<controller>/5  
  27.         [HttpGet]  
  28.         [Route("GetEmployee/{employeeId}")]  
  29.         public IHttpActionResult GetEmployee(string employeeID)  
  30.         {  
  31.             Employee objEmp = new Employee();  
  32.             var EmployeID = Convert.ToInt32(employeeID);  
  33.             try  
  34.             {  
  35.                 objEmp = objEntity.Employees.Find(EmployeID);  
  36.                 if (objEmp == null)  
  37.                 {  
  38.                     return NotFound();  
  39.                 }  
  40.   
  41.             }  
  42.             catch (Exception)  
  43.             {  
  44.                 throw;  
  45.             }  
  46.   
  47.             return Ok(objEmp);  
  48.         }  
  49.         // POST api/<controller>  
  50.         [HttpPost]  
  51.         [Route("InsertEmployee")]  
  52.         public IHttpActionResult PostEmployee(Employee data)  
  53.         {  
  54.   
  55.             if (!ModelState.IsValid)  
  56.             {  
  57.                 return BadRequest(ModelState);  
  58.             }  
  59.             try  
  60.             {  
  61.                 objEntity.Employees.Add(data);  
  62.                 objEntity.SaveChanges();  
  63.             }  
  64.             catch (Exception)  
  65.             {  
  66.                 throw;  
  67.             }  
  68.   
  69.   
  70.   
  71.             return Ok(data);  
  72.         }  
  73.         // PUT api/<controller>/5  
  74.         [HttpPut]  
  75.         [Route("UpdateEmployee")]  
  76.         public IHttpActionResult UpdateEmployee(Employee employee)  
  77.         {  
  78.             if (!ModelState.IsValid)  
  79.             {  
  80.                 return BadRequest(ModelState);  
  81.             }  
  82.   
  83.             try  
  84.             {  
  85.                 Employee objEmp = new Employee();  
  86.                 objEmp = objEntity.Employees.Find(employee.EmployeeID);  
  87.                 if (objEmp != null)  
  88.                 {  
  89.                     objEmp.LastName = employee.LastName;  
  90.                     objEmp.FirstName = employee.FirstName;  
  91.                     objEmp.Title = employee.Title;  
  92.                     objEmp.TitleOfCourtesy = employee.TitleOfCourtesy;  
  93.                     objEmp.BirthDate = employee.BirthDate;  
  94.                     objEmp.HireDate = employee.HireDate;  
  95.                     objEmp.Address = employee.Address;  
  96.                     objEmp.City = employee.City;  
  97.                     objEmp.Region = employee.Region;  
  98.                     objEmp.PostalCode = employee.PostalCode;  
  99.                     objEmp.Country = employee.Country;  
  100.                     objEmp.HomePhone = employee.HomePhone;  
  101.                     objEmp.Notes = employee.Notes;  
  102.                 }  
  103.                 var i = this.objEntity.SaveChanges();  
  104.   
  105.             }  
  106.             catch (Exception)  
  107.             {  
  108.                 throw;  
  109.             }  
  110.             return Ok(employee);  
  111.         }  
  112.         // DELETE api/<controller>/5  
  113.         [HttpDelete]  
  114.         [Route("DeleteEmployee")]  
  115.         public IHttpActionResult DeleteEmployee(int employeeID)  
  116.         {              
  117.             Employee employee = objEntity.Employees.Find(employeeID);  
  118.             if (employee == null)  
  119.             {  
  120.                 return NotFound();  
  121.             }  
  122.   
  123.             objEntity.Employees.Remove(employee);  
  124.             objEntity.SaveChanges();  
  125.   
  126.             return Ok(employee);  
  127.         }  
  128.     }  
  129. }  
Now try to hit a Web API function to get the data, you will get this error,
 
Angular 8 - CRUD Operations
 
To remove this error, add these lines of code on Global.asax file in Application_Start function.
  1. GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings  
  2.   .ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;  
  3.           GlobalConfiguration.Configuration.Formatters  
  4.               .Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);  
Now try to hit the function again, then you will able to see the data in JSON format.
 

Enable CORS

 
This is an important part when you create a new Web API. CORS stands for Cross-Origin Resource Sharing. It is a mechanism that allows restricted resources on a web page to be requested from another domain, outside the domain from which the resource originated. A web page may freely embed images, stylesheets, scripts, iframes, and videos.
 
For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest follows the same-origin policy. So, a web application using XMLHttpRequest could only make HTTP requests to its own domain. To improve web applications, developers asked browser vendors to allow XMLHttpRequest to make cross-domain requests.
 

Enable CORS

 
Now let's 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,
 
Install-Package Microsoft.AspNet.WebApi.Cors
 
Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method,
  1. public static void Register(HttpConfiguration config)  
  2.         {  
  3.             // New code  
  4.             config.EnableCors();  
  5.   
  6.             config.Routes.MapHttpRoute(  
  7.                 name: "DefaultApi",  
  8.                 routeTemplate: "api/{controller}/{id}",  
  9.                 defaults: new { id = RouteParameter.Optional }  
  10.             );  
  11.         }  
OR,
  1. public static void Register(HttpConfiguration config)  
  2.       {  
  3.           var cors = new EnableCorsAttribute("*""*""*");// origins, headers, methods    
  4.           config.EnableCors(cors);  
  5.           // Web API configuration and services  
  6.   
  7.           // Web API routes  
  8.           config.MapHttpAttributeRoutes();  
  9.   
  10.           config.Routes.MapHttpRoute(  
  11.               name: "DefaultApi",  
  12.               routeTemplate: "api/{controller}/{id}",  
  13.               defaults: new { id = RouteParameter.Optional }  
  14.           );  
  15.       }  
Now we are done with WEB API part, let’s move on Angular Service part.
 

Angular Services

 
The main use of services is to organize and share business logic, models or data and functions with different components of an Angular application. Angular services are singleton objects (it is very important, so we can share it easily through project) which get instantiated only once during the lifetime of an application. They contain methods that maintain data throughout the life of an application, i.e. data does not get refreshed and is available all the time.
 
Let’s create a new Service and call Web API functions in it.
 
The best way to create a Service in Angular is with Visual Studio Code. Go to Terminal and hit the command, that will add a new service in an application.
 
Angular 8 - CRUD Operations
 
No go to employee.service.ts file and add the following code,
  1. import { Injectable } from '@angular/core';  
  2. import { HttpClient } from '@angular/common/http';  
  3. import { HttpHeaders } from '@angular/common/http';  
  4. import { Observable } from 'rxjs';  
  5. import { Employee } from './employee';  
  6.   
  7. @Injectable({  
  8.   providedIn: 'root'  
  9. })  
  10. export class EmployeeService {  
  11.   url = 'http://localhost:49210/Api/Employee';  
  12.   
  13.   constructor(private http: HttpClient) { }  
  14.   
  15.   getEmployees(): Observable<Employee[]> {  
  16.     return this.http.get<Employee[]>(this.url + '/GetEmployees');  
  17.   }  
  18.   
  19.   getEmployee(employeeId: string): Observable<Employee> {  
  20.     return this.http.get<Employee>(this.url + '/GetEmployee/' + employeeId);  
  21.   }  
  22.   createEmployee(employee: Employee): Observable<Employee> {  
  23.     const httpOptions = { headers: new HttpHeaders({ 'Content-Type''application/json' }) };  
  24.     return this.http.post<Employee>(this.url + '/InsertEmployee/', employee, httpOptions);  
  25.   }  
  26.   
  27.   updateEmployee(employee: Employee): Observable<Employee> {  
  28.     const httpOptions = { headers: new HttpHeaders({ 'Content-Type''application/json' }) };  
  29.     return this.http.put<Employee>(this.url + '/UpdateEmployee/', employee, httpOptions);  
  30.   }  
  31.   
  32.   deleteEmployee(employeeid: string): Observable<number> {  
  33.     const httpOptions = { headers: new HttpHeaders({ 'Content-Type''application/json' }) };  
  34.     return this.http.delete<number>(this.url + '/DeleteEmployee?id=' + employeeid, httpOptions);  
  35.   }  
  36. }  
In a given service class, we have file function for CRUD operations along with Web API root path. You can change api root path according to your API. We are done here with Angular Service part.
 

Conclusion

 
In this article, we have learned about angular routing, services and how to make Web API using Entity framework with SQL Server database. The next part is  coming with Angular implementation for CRUD operations. Stay tuned!