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. GetProducts():Observable<ProductDTO[]>{
  12. return this.httpclient.get<ProductDTO[]>(this.ApiUrl+'Api/Product/GetProducts');
  13. }
  14. GetProductById(Id:string):Observable<ProductDTO>{
  15. return this.httpclient.get<ProductDTO>(this.ApiUrl+'Api/Product/GetProductById/'+Id);
  16. }
  17. InsertProduct(product:ProductDTO){
  18. return this.httpclient.post<ProductDTO>(this.ApiUrl+'Api/Product/InsertProduct',product);
  19. }
  20. UpdateProduct(product:ProductDTO):Observable<ProductDTO>{
  21. return this.httpclient.put<ProductDTO>(this.ApiUrl+'Api/Product/Updateproduct/',product);
  22. }
  23. DeleteProduct(Id:string){
  24. return this.httpclient.delete(this.ApiUrl+'Api/Product/DeleteProduct/'+Id);
  25. }
  26. UserAuthentication(UserName: string,Password: string):Observable<any>{
  27. let credentials='username=' +UserName + '&password=' +Password +'&grant_type=password';
  28. var reqHeader = new HttpHeaders({'Content-Type': 'application/x-www-urlencoded','No-Auth':'True' });
  29. return this.httpclient.post<any>(this.ApiUrl+'token',encodeURI(credentials),{headers:reqHeader});
  30. }
  31. }
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. @Component({
  6. selector: 'app-login',
  7. templateUrl: './login.component.html',
  8. styleUrls: ['./login.component.less']
  9. })
  10. export class LoginComponent implements OnInit {
  11. constructor(private productService:ProductService, private router:Router) { }
  12. ngOnInit() {
  13. if(window.sessionStorage.getItem('userToken')!=null){
  14. this.router.navigate(['/Product']);
  15. }
  16. }
  17. LoginForm=new FormGroup({
  18. UserName: new FormControl('',Validators.required),
  19. Password: new FormControl('',Validators.required),
  20. });
  21. OnGetToken(){
  22. const user=this.LoginForm.controls['UserName'].value;
  23. const pass=this.LoginForm.controls['Password'].value;
  24. this.productService.UserAuthentication(user,pass).subscribe((data:any)=>{
  25. window.sessionStorage.setItem('userToken',data.access_token);
  26. this.router.navigate(['/Product']);
  27. });
  28. }
  29. }
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. constructor(private productservice: ProductService) { }
  12. ngOnInit() {
  13. this.GetAllProducts();
  14. }
  15. ProductList:ProductDTO[];
  16. product:ProductDTO;
  17. productIdUpdate = null;
  18. ProductForm=new FormGroup({
  19. Name: new FormControl('',Validators.required),
  20. Price: new FormControl(''),
  21. });
  22. OnSubmit(){
  23. if(this.productIdUpdate==null){
  24. const product=this.ProductForm.value;
  25. this.InsertProduct(product);
  26. }
  27. else{
  28. const employee=this.ProductForm.value;
  29. this.UpdateProduct(employee);
  30. }
  31. }
  32. GetAllProducts(){
  33. this.productservice.GetProducts().subscribe(data=>{this.ProductList=data;});
  34. }
  35. GetProductById(Id:string){
  36. this.productservice.GetProductById(Id).subscribe(data=>{
  37. this.SetProductFormValues(data);
  38. });
  39. }
  40. SetProductFormValues(product: ProductDTO){
  41. this.ProductForm.controls['Name'].setValue(product.Name);
  42. this.ProductForm.controls['Price'].setValue(product.Price);
  43. this.productIdUpdate=product.ID;
  44. }
  45. InsertProduct(product:ProductDTO){
  46. this.productservice.InsertProduct(product).subscribe(()=>{
  47. this.GetAllProducts();
  48. });
  49. }
  50. UpdateProduct(product:ProductDTO){
  51. product.ID=this.productIdUpdate;
  52. this.productservice.UpdateProduct(product).subscribe(()=>{
  53. this.productIdUpdate=null;
  54. this.GetAllProducts();
  55. });
  56. }
  57. DeleteProduct(Id:string){
  58. this.productservice.DeleteProduct(Id).subscribe(()=>{
  59. this.productIdUpdate=null;
  60. this.GetAllProducts();
  61. });
  62. }
  63. }
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. const routes: Routes = [
  6. {path:'', redirectTo:'/Product',pathMatch:'full'},
  7. {path:'Product', component:ProductComponent},
  8. {path:'Login', component:LoginComponent}
  9. ];
  10. @NgModule({
  11. imports: [RouterModule.forRoot(routes)],
  12. exports: [RouterModule]
  13. })
  14. 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. @Injectable()
  6. export class AuthInterceptor implements HttpInterceptor{
  7. constructor(private router:Router){}
  8. intercept(req: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>>
  9. {
  10. if(req.headers.get('No-Auth') == "True")
  11. {
  12. return next.handle(req.clone());
  13. }
  14. if(window.sessionStorage.getItem('userToken')!=null){
  15. const clonedReq=req.clone({
  16. headers:req.headers.set("Authorization","Bearer " +window.sessionStorage.getItem('userToken'))
  17. });
  18. return next.handle(clonedReq);
  19. }
  20. else{
  21. this.router.navigateByUrl("/Login");
  22. }
  23. }
  24. }
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. enableProdMode();
  13. @NgModule({
  14. declarations: [
  15. AppComponent,
  16. ProductComponent,
  17. LoginComponent
  18. ],
  19. imports: [
  20. BrowserModule,
  21. AppRoutingModule,
  22. ReactiveFormsModule,
  23. HttpClientModule
  24. ],
  25. providers: [ProductService
  26. ,
  27. {
  28. provide:HTTP_INTERCEPTORS,
  29. useClass:AuthInterceptor,
  30. multi:true
  31. }
  32. ],
  33. bootstrap: [AppComponent]
  34. })
  35. 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(29, 202, 52);
  3. }
  4. table{
  5. border-collapse: collapse;
  6. width: 90%;
  7. }
  8. th{
  9. height: 50px;
  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.
<< Previous Part Angular 8 CRUD with Oauth2.0 in WebAPI Part One