Angular 8 CRUD With OAuth2.0 In WebAPI - Part Two

Introduction

In the previous article, we have created a Web API and connected that with DB. Also, we have secured the Web API using the OAuth2.0 technique. Now, in this part, we will consume that API using an Angular app in the front-end.
The complete project code is given at this link below.

How will it work?

 
First of all, we have to configure the environment to start development in Angular. I hope you already configured the environment. Please download the latest version of NodeJS. I’m using Visual Studio Code as my code editor but you can choose any other or this one. So, let’s create an Angular app using Angular CLI.
 
Open Visual Studio Code terminal or command prompt and run through the following steps.
 
Step 1
 
Create an Angular project. Open cmd or VS Code terminal and type the command - ng new AngularAuth
 
Angular 8 CRUD With Oauth2.0 In WebAPI
 
Step 2
 
Type (Y) to add routing module
 
Angular 8 CRUD With Oauth2.0 In WebAPI
 
Step 3
 
Choose stylesheet type
 
Angular 8 CRUD With Oauth2.0 In WebAPI
 
Step 4
 
Now our project is created successfully now let’s run the project. Type the command,
 
cd AngularCRUD
ng serve –open
 
Angular 8 CRUD With Oauth2.0 In WebAPI
 
The Browser will display this page which means the project created and ran successfully.
 
Angular 8 CRUD With Oauth2.0 In WebAPI
Step 5
 
Let’s create a DTO class ProductDTO.ts
 
Angular 8 CRUD With Oauth2.0 In WebAPI
 
ProductDTO.ts
  1. export class ProductDTO{    
  2.     ID: string;      
  3.     Name: string;      
  4.     Price: string;      
  5. }  
Step 6
 
Let’s create a service class for communication with the database.
 
Type the command: ng g service Product.
 
Angular 8 CRUD With Oauth2.0 In WebAPI
 
ProductService.ts
  1. import { Injectable } from '@angular/core';    
  2. import {HttpClient,HttpHeaders} from '@angular/common/http';    
  3. import { ProductDTO } from '../app/ProductDTO';    
  4. import { Observable } from 'rxjs';    
  5. @Injectable({    
  6.   providedIn: 'root'    
  7. })    
  8. export class ProductService {    
  9.   ApiUrl='http://localhost:57046/';    
  10.   constructor(private httpclient: HttpClient) { }    
  11.     
  12.   GetProducts():Observable<ProductDTO[]>{    
  13.   return this.httpclient.get<ProductDTO[]>(this.ApiUrl+'Api/Product/GetProducts');    
  14.   }    
  15.     
  16.   GetProductById(Id:string):Observable<ProductDTO>{    
  17.     return this.httpclient.get<ProductDTO>(this.ApiUrl+'Api/Product/GetProductById/'+Id);    
  18.   }    
  19.    InsertProduct(product:ProductDTO){    
  20.    return this.httpclient.post<ProductDTO>(this.ApiUrl+'Api/Product/InsertProduct',product);    
  21. }    
  22.     
  23.   UpdateProduct(product:ProductDTO):Observable<ProductDTO>{    
  24.     return this.httpclient.put<ProductDTO>(this.ApiUrl+'Api/Product/Updateproduct/',product);    
  25.   }    
  26.     
  27.   DeleteProduct(Id:string){    
  28.     return this.httpclient.delete(this.ApiUrl+'Api/Product/DeleteProduct/'+Id);    
  29.   }    
  30.     
  31.   UserAuthentication(UserName: string,Password: string):Observable<any>{    
  32.    let credentials='username=' +UserName  + '&password=' +Password +'&grant_type=password';     
  33.    var reqHeader = new HttpHeaders({'Content-Type''application/x-www-urlencoded','No-Auth':'True' });    
  34.   return this.httpclient.post<any>(this.ApiUrl+'token',encodeURI(credentials),{headers:reqHeader});    
  35. }    
  36. }   
Step 7
 
Now, let’s create a Login Component; type the command - ng g component Login
 
Angular 8 CRUD With Oauth2.0 In WebAPI
 
LoginComponent.ts
  1. import { Component, OnInit } from '@angular/core';    
  2. import { ProductService } from '../product.service';    
  3. import { FormControl,FormGroup,Validators } from '@angular/forms';    
  4. import { Router} from '@angular/router';    
  5.     
  6. @Component({    
  7.   selector: 'app-login',    
  8.   templateUrl: './login.component.html',    
  9.   styleUrls: ['./login.component.less']    
  10. })    
  11. export class LoginComponent implements OnInit {    
  12.     
  13.   constructor(private productService:ProductService, private router:Router) { }    
  14.     
  15.   ngOnInit() {    
  16.     if(window.sessionStorage.getItem('userToken')!=null){    
  17.       this.router.navigate(['/Product']);    
  18.     }    
  19.   }     
  20.   LoginForm=new FormGroup({    
  21.     UserName: new FormControl('',Validators.required),    
  22.     Password: new FormControl('',Validators.required),    
  23.    });     
  24.  OnGetToken(){    
  25.    const user=this.LoginForm.controls['UserName'].value;    
  26.    const pass=this.LoginForm.controls['Password'].value;    
  27.   this.productService.UserAuthentication(user,pass).subscribe((data:any)=>{    
  28.   window.sessionStorage.setItem('userToken',data.access_token);    
  29.   this.router.navigate(['/Product']);    
  30.   });    
  31.   }    
  32. }   
Step 8
 
Paste this code in LoginComponent.html file.
  1. <form [formGroup]="LoginForm" (ngSubmit)="OnGetToken()">    
  2.     <div>    
  3.      <Label>    
  4.      UserName    
  5.     <input type="text" formControlName="UserName">    
  6.     </Label>    
  7.     </div>    
  8.     <div>    
  9.     <label>    
  10.         Password    
  11.         <input type="password" formControlName="Password">    
  12.     </label>    
  13.     </div>    
  14.     <div>    
  15.     <button type="submit" [disabled]="!LoginForm.valid"> Login</button>    
  16.     </div>    
  17. </form>   
Step 9
 
Create Product component, type the command - ng g component Product
 
Angular 8 CRUD With Oauth2.0 In WebAPI
 
ProductComponent.ts
  1. import { Component, OnInit } from '@angular/core';    
  2. import { ProductService } from '../product.service';    
  3. import { ProductDTO } from '../ProductDTO';    
  4. import { FormGroup,FormControl,Validators } from '@angular/forms';    
  5. @Component({    
  6.   selector: 'app-product',    
  7.   templateUrl: './product.component.html',    
  8.   styleUrls: ['./product.component.less']    
  9. })    
  10. export class ProductComponent implements OnInit {    
  11.     
  12.   constructor(private productservice: ProductService) { }    
  13.     
  14.   ngOnInit() {    
  15.     this.GetAllProducts();    
  16.   }    
  17.   ProductList:ProductDTO[];    
  18.   product:ProductDTO;    
  19.   productIdUpdate = null;    
  20.   ProductForm=new FormGroup({    
  21.     Name: new FormControl('',Validators.required),    
  22.     Price: new FormControl(''),    
  23.    });     
  24.    OnSubmit(){    
  25.     if(this.productIdUpdate==null){    
  26.        const product=this.ProductForm.value;    
  27.        this.InsertProduct(product);    
  28.     }    
  29.     else{    
  30.        const employee=this.ProductForm.value;    
  31.        this.UpdateProduct(employee);    
  32.     }    
  33.  }    
  34.      
  35.  GetAllProducts(){    
  36.        
  37.     this.productservice.GetProducts().subscribe(data=>{this.ProductList=data;});    
  38.  }    
  39.  GetProductById(Id:string){    
  40.     this.productservice.GetProductById(Id).subscribe(data=>{    
  41.        this.SetProductFormValues(data);     
  42.     });     
  43.        
  44.  }    
  45.  SetProductFormValues(product: ProductDTO){    
  46.   this.ProductForm.controls['Name'].setValue(product.Name);    
  47.   this.ProductForm.controls['Price'].setValue(product.Price);    
  48.   this.productIdUpdate=product.ID;    
  49.  }    
  50.  InsertProduct(product:ProductDTO){    
  51.     this.productservice.InsertProduct(product).subscribe(()=>{    
  52.        this.GetAllProducts();    
  53.     });    
  54.  }    
  55.  UpdateProduct(product:ProductDTO){    
  56.    product.ID=this.productIdUpdate;    
  57.   this.productservice.UpdateProduct(product).subscribe(()=>{    
  58.     this.productIdUpdate=null;    
  59.     this.GetAllProducts();    
  60.   });    
  61.  }    
  62.  DeleteProduct(Id:string){    
  63.   this.productservice.DeleteProduct(Id).subscribe(()=>{    
  64.     this.productIdUpdate=null;    
  65.     this.GetAllProducts();    
  66.   });    
  67.  }    
  68. }    
Step 10
 
Paste this code in ProductComponent.html.
 
ProductComponent.html
  1. <form [formGroup]="ProductForm" (ngSubmit)="OnSubmit()">    
  2.     <div>    
  3.     <label>    
  4.       Name    
  5.         <input type="text" formControlName="Name">    
  6.     </label>    
  7.   </div>    
  8.   <div style="margin-top: 20px">    
  9.     <label>    
  10.      Price    
  11.         <input type="text" formControlName="Price">    
  12.     </label>    
  13.   </div>    
  14.    <div>    
  15.       <button type="submit" [disabled]="!ProductForm.valid">Save</button>    
  16.    </div>    
  17.   </form>    
  18.   <table>    
  19.     <tr>    
  20.     <th>    
  21.       Name    
  22.     </th>    
  23.     <th>    
  24.      Price    
  25.     </th>    
  26.     <th>    
  27.       Update Record    
  28.     </th>    
  29.     <th>    
  30.         Delete Record    
  31.       </th>    
  32.   </tr>    
  33.   <tr *ngFor="let item of ProductList">    
  34.   <td>    
  35.       {{item.Name}}    
  36.     </td>    
  37.     <td>    
  38.         {{item.Price}}    
  39.       </td>    
  40.       <td>    
  41.         <button type="button" (click)="GetProductById(item.ID)">Edit</button>      
  42.       </td>    
  43.       <td>    
  44.           <button type="button" (click)="DeleteProduct(item.ID)">Delete</button>      
  45.       </td>    
  46.   </tr>    
  47. </table>    
Step 11
 
Open app-routing.module.ts file and paste this code.
  1. import { NgModule } from '@angular/core';    
  2. import { Routes, RouterModule } from '@angular/router';    
  3. import { ProductComponent} from '../app/product/product.component';    
  4. import {LoginComponent} from '../app/login/login.component';    
  5.     
  6. const routes: Routes = [    
  7.   {path:'', redirectTo:'/Product',pathMatch:'full'},    
  8.    {path:'Product', component:ProductComponent},    
  9.    {path:'Login', component:LoginComponent}    
  10.  ];    
  11.     
  12. @NgModule({    
  13.   imports: [RouterModule.forRoot(routes)],    
  14.   exports: [RouterModule]    
  15. })    
  16. export class AppRoutingModule { }    
Step 12
 
Create a new file with the name as auth.interceptor.ts file and paste this code.
  1. import { HttpInterceptor,HttpHandler,HttpEvent,HttpRequest } from '@angular/common/http';    
  2. import { Injectable } from '@angular/core';    
  3. import { Router } from '@angular/router';    
  4. import { Observable } from 'rxjs';    
  5.     
  6.     
  7. @Injectable()    
  8. export class AuthInterceptor implements HttpInterceptor{    
  9.     
  10.     constructor(private router:Router){}    
  11.     intercept(req: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>>    
  12.     {    
  13.      if(req.headers.get('No-Auth') == "True")    
  14.      {    
  15.         return next.handle(req.clone());    
  16.      }       
  17.     
  18.      if(window.sessionStorage.getItem('userToken')!=null){    
  19.         const clonedReq=req.clone({    
  20.           headers:req.headers.set("Authorization","Bearer " +window.sessionStorage.getItem('userToken'))    
  21.          });    
  22.          return next.handle(clonedReq);    
  23.      }    
  24.      else{    
  25.       this.router.navigateByUrl("/Login");    
  26.      }    
  27.     }    
  28. }   
Step 13
 
Open app.module.ts class and paste this code.
  1. import { BrowserModule } from '@angular/platform-browser';    
  2. import { NgModule } from '@angular/core';    
  3. import { AppRoutingModule } from './app-routing.module';    
  4. import { AppComponent } from './app.component';    
  5. import { ProductComponent } from './product/product.component';    
  6. import { LoginComponent } from './login/login.component';    
  7. import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';    
  8. import { ReactiveFormsModule } from '@angular/forms';    
  9. import { ProductService } from './product.service';    
  10. import { AuthInterceptor } from '../app/auth.interceptor';    
  11. import {enableProdMode} from '@angular/core';    
  12.     
  13. enableProdMode();    
  14. @NgModule({    
  15.   declarations: [    
  16.     AppComponent,    
  17.     ProductComponent,    
  18.     LoginComponent    
  19.   ],    
  20.   imports: [    
  21.     BrowserModule,    
  22.     AppRoutingModule,    
  23.     ReactiveFormsModule,    
  24.     HttpClientModule    
  25.   ],    
  26.   providers: [ProductService    
  27.     ,    
  28.   {    
  29.    provide:HTTP_INTERCEPTORS,    
  30.    useClass:AuthInterceptor,    
  31.    multi:true    
  32.   }    
  33. ],    
  34.   bootstrap: [AppComponent]    
  35. })    
  36. export class AppModule { }    
Step 14
 
Open the app.component.html file, remove all the code except only one tag <router-outlet></router-outlet>.
 
Step 15
 
Open the productcomponent.less stylesheet file and paste this code.
  1. table, td, th{  
  2.     border:1px solid rgb(2920252);  
  3.   }  
  4.   table{  
  5.     border-collapsecollapse;  
  6.     width90%;  
  7.   }  
  8.   th{  
  9.     height50px;  
  10.   } 
Stylesheet and all other files are highlighted
 
Angular 8 CRUD With Oauth2.0 In WebAPI
 
Step 16
 
Now just save all the data and refresh the browser. You will see the login page. Once you pass the username and password, the browser will redirect to the Product page.

Angular 8 CRUD With Oauth2.0 In WebAPI

Conclusion

 
In this article, we have performed complete CRUD operations in Angular 8. Also, we learned how we retrieve the authorized token from the WebAPI and add in the header of the HTTP request and perform all the operations by passing the Oauth Token. If you face any problem or have any query, please comment in the comment section below. Please don’t forget to like and share it.