Interceptor In Angular

Introduction

 
HttpInterceptors are use to handle and intercpts the HttpRequest and HttpResponse.
 
In this article we will try to use the HttpInterceptors for the following reasons,
  1. Creating an Error Interceptor.
  2. Creating JSON Web Tokens (JWT)interceptor.
  3. Creating a Fake-Backend Service with Interceptor.
Let’s create an application(called as Event Management) which will demonstrate the use of these Interceptors.
 
Application will have the following functionalities,
  1. Register of user
  2. Login
  3. Authentication of user
  4. Events list
  5. Paid (Members) event list.
  6. AuthGuard for routing.
Let’s create an application.
 
ng new AuthApp
 
Create below components with Angular CLI command,
  1. Register ( ng g c register )
  2. Login
  3. Logout
  4. Events
  5. Paid-events
Create folders
  1. _guards ( to keep the auth guard file )
  2. _helpers ( To keep the Interceptors )
  3. _model ( to keep the models )
  4. _services ( To keep the services )
  1. Create class user inside _model directory.  
  2. export class User {  
  3.     id: number;  
  4.     username: string;  
  5.     password: string;  
  6.     firstName: string;  
  7.     lastName: string;  
  8.     isAdmin: boolean;  
  9.     token: string;  

Add auth.service.ts through command inside _services directory,
  1. import { Injectable } from '@angular/core';  
  2. import { HttpClient } from '@angular/common/http';  
  3. import { map } from 'rxjs/operators';  
  4. import { Observable, BehaviorSubject } from 'rxjs';  
  5. import { User } from '../_model/user';  
  6.   
  7. @Injectable({  
  8.   providedIn: 'root'  
  9. })  
  10. export class AuthService {  
  11.   
  12.   private currentUserSubject: BehaviorSubject<User>;  
  13.   public currentUser: Observable<User>;  
  14.   private _loginUrl = "api/login";  
  15.   private _registerUrl = "api/register";  
  16.   constructor(private http: HttpClient) {  
  17.     this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(sessionStorage.getItem('currentUser')));  
  18.     this.currentUser = this.currentUserSubject.asObservable();  
  19. }  
  20.   
  21.   public get currentUserValue(): User {  
  22.     return this.currentUserSubject.value;  
  23.   }  
  24.   
  25.   getAuthToken(){  
  26.     return "TOKEN-001001010100111";  
  27.   }  
  28.   registerUser(user) {  
  29.     return this.http.post<any>(this._registerUrl, user);  
  30.   }  
  31.   login(user) {  
  32.     return this.http.post<any>(this._loginUrl, user);  
  33.   }  
  34.   
  35.   authenticate(loginData) {  
  36.     return this.http.post<any>("http://localhost:4200/api/login", loginData)  
  37.         .pipe(map(user => {  
  38.             // login successful if there's a jwt token in the response  
  39.             if (user && user.token) {  
  40.                 // store user details and jwt token in local storage to keep user logged in between page refreshes  
  41.                 sessionStorage.setItem('currentUser', JSON.stringify(user));  
  42.                 this.currentUserSubject.next(user);  
  43.             }  
  44.   
  45.             return user;  
  46.         }));  
  47.       }  
  48.         
  49.       logout() {  
  50.         // remove user from local storage to log user out  
  51.         sessionStorage.removeItem('currentUser');  
  52.         this.currentUserSubject.next(null);  
  53.     }  

Create event.service.ts through command inside _services directory,
  1. import { Injectable } from '@angular/core';  
  2. import { HttpClient } from '@angular/common/http';  
  3.   
  4. @Injectable({  
  5.   providedIn: 'root'  
  6. })  
  7. export class EventService {  
  8.   
  9.   private _eventsUrl = "api/events";  
  10.   private _paidEventsUrl = "api/paidEvents";  
  11.   
  12.   constructor(private http: HttpClient) { }  
  13.   
  14.   getEvents() {  
  15.     return this.http.get<any>(this._eventsUrl);  
  16.   }  
  17.   
  18.   getPaidEvents() {  
  19.     return this.http.get<any>(this._paidEventsUrl);  
  20.   }  

Create file auth.guard.ts in _guard directory and add the below contents,
  1. import { Injectable } from '@angular/core';  
  2. import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';  
  3. import { AuthService } from '../_services/auth.service';  
  4.   
  5. @Injectable({ providedIn: 'root' })  
  6. export class AuthGuard implements CanActivate {  
  7.     constructor(  
  8.         private router: Router,  
  9.         private authenticationService: AuthService  
  10.     ) {}  
  11.   
  12.     canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {  
  13.         console.log("CanActivate method called from class AuthGuard..");  
  14.           
  15.         const currentUser = this.authenticationService.currentUserValue;  
  16.         if (currentUser) {  
  17.   
  18.             this.router.navigate(['/paidevents'], { queryParams: { returnUrl: state.url }});  
  19.             // authorised so return true  
  20.             return true;  
  21.         }  
  22.   
  23.         // not logged in so redirect to login page with the return url  
  24.         this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});  
  25.         return false;  
  26.     }  

Create error.interceptors.ts in _helpers directory,
  1. import { Injectable } from '@angular/core';  
  2. import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';  
  3. import { Observable, throwError } from 'rxjs';  
  4. import { catchError } from 'rxjs/operators';  
  5. import { AuthService } from '../_services/auth.service';  
  6. import { Router } from '@angular/router';  
  7.   
  8. @Injectable()  
  9. export class ErrorInterceptor implements HttpInterceptor {  
  10.     constructor(private authenticationService: AuthService, private router: Router) { }  
  11.   
  12.     intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {  
  13.           
  14.         return next.handle(request).pipe(catchError(err => {  
  15.             if (err.status === 401) {  
  16.                 this.authenticationService.logout();  
  17.                 this.router.navigate(['/login']);  
  18.             }  
  19.   
  20.             const error = err.error.message || err.statusText;  
  21.             return throwError(error);  
  22.         }))  
  23.     }  

Create jwt.interceptor.ts in _helpers directory.
  1. import { Injectable } from '@angular/core';  
  2. import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';  
  3. import { Observable } from 'rxjs';  
  4. import { AuthService } from '../_services/auth.service';  
  5.   
  6. @Injectable()  
  7. export class JwtInterceptor implements HttpInterceptor {  
  8.     constructor(private authenticationService: AuthService) { }  
  9.   
  10.     intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {  
  11.         console.log("Intercept method called from JWTInterceptor..");  
  12.         // add authorization header with jwt token if available  
  13.         let currentUser = this.authenticationService.currentUserValue;  
  14.         if (currentUser && currentUser.token) {  
  15.             request = request.clone({  
  16.                 setHeaders: {  
  17.                     Authorization: `Bearer ${currentUser.token}`,  
  18.                     admin: "Irshad",  
  19.                     Host: "localhost://3400"  
  20.                 }  
  21.             });  
  22.         }  
  23.         return next.handle(request);  
  24.     }  

Create fake-backend-intercepter.provider.ts in _helpers directory,
  1. import { Injectable } from '@angular/core';  
  2. import { HttpRequest, HttpResponse, HttpHandler, HttpEvent, HttpInterceptor, HTTP_INTERCEPTORS } from '@angular/common/http';  
  3. import { Observable, of, throwError } from 'rxjs';  
  4. import { delay, mergeMap, materialize, dematerialize } from 'rxjs/operators';  
  5. import * as jwt_decode from 'jwt-decode';  
  6.   
  7. // array in local storage for registered users  
  8. let users = JSON.parse(localStorage.getItem('users')) || [];  
  9.   
  10. @Injectable()  
  11. export class FakeBackendInterceptor implements HttpInterceptor {  
  12.     constructor(){}  
  13.   
  14.       
  15.     intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {  
  16.         // Token for admin user  
  17.         const adminToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEiLCJ1c2VybmFtZSI6ImFkbWluIiwiZmlyc3ROYW1lIjoiTW9oYW1tYWQiLCJsYXN0TmFtZSI6Iklyc2hhZCJ9.apXr_qMJrzvYczZbfW23UfJdzmMaaCA8d7Njm8tN9wI";  
  18.         // Token for non-admin users  
  19.         const userToken = "fake-jwt-token";  
  20.         const { url, method, headers, body } = request;  
  21.         return of(null)  
  22.             .pipe(mergeMap(handleRoute))  
  23.             .pipe(materialize())   
  24.             .pipe(delay(500))  
  25.             .pipe(dematerialize());  
  26.   
  27.         function handleRoute() {  
  28.             switch (true) {  
  29.                 case url.endsWith('/api/login') && method === 'POST':  
  30.                     return authenticate();  
  31.                 case url.endsWith('api/register') && method === 'POST':  
  32.                     return register();  
  33.                 case url.endsWith('/users') && method === 'GET':  
  34.                     return getUsers();  
  35.                 case url.endsWith('/events') && method === 'GET':  
  36.                     return getEvents();  
  37.                 case url.endsWith('/paidEvents') && method === 'GET':  
  38.                     return getPaidEvents();  
  39.                 case url.match(/\/users\/\d+$/) && method === 'DELETE':  
  40.                     return deleteUser();  
  41.                 default:  
  42.                     return next.handle(request);  
  43.             }      
  44.         }  
  45.   
  46.         function authenticate() {  
  47.             const { username, password } = body;  
  48.             if(username=='admin' && password=='1'){  
  49.                 var admin = jwt_decode(adminToken);  
  50.                 admin.isAdmin = true;  
  51.                 admin.token = adminToken;  
  52.                 return ok(admin);  
  53.             }   
  54.             const user = users.find(x => x.username === username && x.password === password);  
  55.             if (!user) return error('Username or password is incorrect');  
  56.               
  57.             return ok({  
  58.                 id: user.id,  
  59.                 username: user.username,  
  60.                 firstName: user.firstName,  
  61.                 lastName: user.lastName,  
  62.                 isAdmin: false,  
  63.                 token: userToken  
  64.             })  
  65.         }  
  66.   
  67.         function register() {  
  68.             const user = body  
  69.   
  70.             if (users.find(x => x.username === user.username)) {  
  71.                 return error('Username "' + user.username + '" is already taken');  
  72.             }  
  73.   
  74.             user.id = users.length ? Math.max(...users.map(x => x.id)) + 1 : 1;  
  75.             user.isAdmin = false;  
  76.             users.push(user);  
  77.             localStorage.setItem('users', JSON.stringify(users));  
  78.   
  79.             return ok('Successfully created');  
  80.         }  
  81.   
  82.         function getUsers() {  
  83.             if (!isLoggedIn()) return unauthorized();  
  84.             return ok(users);  
  85.         }  
  86.   
  87.         function deleteUser() {  
  88.             if (!isLoggedIn()) return unauthorized();  
  89.   
  90.             users = users.filter(x => x.id !== idFromUrl());  
  91.             localStorage.setItem('users', JSON.stringify(users));  
  92.             return ok();  
  93.         }  
  94.   
  95.         function ok(body?) {  
  96.             return of(new HttpResponse({ status: 200, body }))  
  97.         }  
  98.   
  99.         function error(message) {  
  100.             return throwError({ error: { message } });  
  101.         }  
  102.   
  103.         function unauthorized() {  
  104.             return throwError({ status: 401, error: { message: 'Unauthorised' } });  
  105.         }  
  106.   
  107.         function isLoggedIn() {  
  108.             return headers.get('Authorization') === 'Bearer ' + userToken || headers.get('Authorization') === 'Bearer '+ adminToken;  
  109.         }  
  110.   
  111.         function getEvents() {  
  112.             return ok(events);  
  113.         }  
  114.   
  115.         function getPaidEvents() {  
  116.             if (!isLoggedIn()) return unauthorized();  
  117.             return ok(paidEvents);  
  118.         }  
  119.   
  120.         function idFromUrl() {  
  121.             const urlParts = url.split('/');  
  122.             return parseInt(urlParts[urlParts.length - 1]);  
  123.         }  
  124.     }  
  125. }  
  126.   
  127. let events = [  
  128.     {  
  129.         "id""1",  
  130.         "name""event1",  
  131.         "place""place1",  
  132.         "date""date1"  
  133.     },  
  134.     {  
  135.         "id""2",  
  136.         "name""event3",  
  137.         "place""place2",  
  138.         "date""date2"  
  139.     },  
  140.     {  
  141.         "id""3",  
  142.         "name""event3",  
  143.         "place""place3",  
  144.         "date""date3"  
  145.     },  
  146.     {  
  147.         "id""4",  
  148.         "name""event4",  
  149.         "place""place4",  
  150.         "date""date4"  
  151.     },  
  152.     {  
  153.         "id""5",  
  154.         "name""event5",  
  155.         "place""place5",  
  156.         "date""date5"  
  157.     }  
  158. ];  
  159.   
  160. let paidEvents = [  
  161.     {  
  162.         "id""1",  
  163.         "name""paidEvent1",  
  164.         "place""place1",  
  165.         "date""date1"  
  166.     },  
  167.     {  
  168.         "id""2",  
  169.         "name""paidEvent3",  
  170.         "place""place2",  
  171.         "date""date2"  
  172.     },  
  173.     {  
  174.         "id""3",  
  175.         "name""paidEvent3",  
  176.         "place""place3",  
  177.         "date""date3"  
  178.     },  
  179.     {  
  180.         "id""4",  
  181.         "name""paidEvent4",  
  182.         "place""place4",  
  183.         "date""date4"  
  184.     },  
  185.     {  
  186.         "id""5",  
  187.         "name""paidEvent5",  
  188.         "place""place5",  
  189.         "date""date5"  
  190.     }  
  191. ];  
  192.   
  193. export const fakeBackendProvider = {  
  194.     // use fake backend in place of Http service for backend-less development  
  195.     provide: HTTP_INTERCEPTORS,  
  196.     useClass: FakeBackendInterceptor,  
  197.     multi: true  
  198. }; 
Create app-routing.module.ts
  1. import { NgModule } from '@angular/core';  
  2. import { Routes, RouterModule } from '@angular/router';  
  3. import { EventsComponent } from './events/events.component';  
  4. import { PaidEventsComponent } from './paid-events/paid-events.component';  
  5. import { LoginComponent } from './login/login.component';  
  6. import { RegisterComponent } from './register/register.component';  
  7. import { AuthGuard } from './_guards/auth.guard';  
  8.   
  9. const routes: Routes = [  
  10.   {  
  11.     path: '',  
  12.     component: EventsComponent,  
  13.     canActivate: [AuthGuard]  
  14.   },  
  15.   {  
  16.     path: 'events',  
  17.     component: EventsComponent,  
  18.   },  
  19.   {  
  20.     path: 'paidevents',  
  21.     component: PaidEventsComponent  
  22.   },  
  23.   {  
  24.     path: 'login',  
  25.     component: LoginComponent  
  26.   },  
  27.   {  
  28.     path: 'register',  
  29.     component: RegisterComponent  
  30.   }  
  31. ];  
  32.   
  33. @NgModule({  
  34.   imports: [RouterModule.forRoot(routes)],  
  35.   exports: [RouterModule]  
  36. })  
  37. export class AppRoutingModule { } 
Let’s start with component html and ts files.
 
Open login.component.ts and add the below contents,
  1. import { Component, OnInit } from '@angular/core';  
  2. import { AuthService } from '../_services/auth.service';  
  3. import { Router } from '@angular/router';  
  4.   
  5. @Component({  
  6.   selector: 'app-login',  
  7.   templateUrl: './login.component.html',  
  8.   styleUrls: ['./login.component.css']  
  9. })  
  10. export class LoginComponent implements OnInit {  
  11.   
  12.   loginData = { username: '', password: ''};  
  13.   constructor(private _authservice: AuthService, private router: Router) {   
  14.     // redirect to paidEvents if already logged in  
  15.     if (this._authservice.currentUserValue) {   
  16.       this.router.navigate(['/paidevents']);  
  17.   }  
  18. }  
  19.   
  20.   ngOnInit(): void {  
  21.   }  
  22.   
  23.   login() {  
  24.     console.log(this.loginData);  
  25.     this._authservice.authenticate(this.loginData).subscribe(  
  26.       data => {  
  27.         console.log("loggedin : ", data );  
  28.         this.router.navigate(['/paidevents'], { queryParams: { }});  
  29.       },  
  30.       error => {  
  31.         console.log("erorr: ", error);  
  32.       }  
  33.     );  
  34.     console.log('Logged in successfully!');  
  35.   }  

Open login.component.html and add the below contents,
  1. <div class="row pt-5">  
  2.     <div class="co-md-6 mx-auto">  
  3.         <div class="card rounded-0">  
  4.             <div class="card-header">  
  5.                 <h3 class="mb-0">Login</h3>  
  6.             </div>  
  7.             <div class="card-body">  
  8.                 <form class="form">  
  9.                     <div class="form-group">  
  10.                         <label for="">Username</label>  
  11.                         <input [(ngModel)]="loginData.username" name="username" type="text" class="form-control rounded-0" required>  
  12.                     </div>  
  13.                     <div class="form-group">  
  14.                         <label for="">Password</label>  
  15.                         <input [(ngModel)]="loginData.password" name="password" type="text" class="form-control rounded-0" required>  
  16.                     </div>  
  17.                     <a routerLink="/register" class="btn btn-primary float-left">Register</a>  
  18.                     <button (click)="login()" type="button" class="btn btn-primary float-right">Login</button>  
  19.                 </form>  
  20.             </div>  
  21.         </div>  
  22.     </div>  
  23. </div> 
Open register.component.ts and add the below contents,
  1. import { Component, OnInit } from '@angular/core';  
  2. import { AuthService } from '../_services/auth.service';  
  3. import { User } from '../_model/user';  
  4. import { Router } from '@angular/router';  
  5. import { Subscription } from 'rxjs';  
  6.   
  7. @Component({  
  8.   selector: 'app-register',  
  9.   host: { '[@slideInOutAnimation]''' },  
  10.   templateUrl: './register.component.html',  
  11.   styleUrls: ['./register.component.css']  
  12. })  
  13. export class RegisterComponent implements OnInit  {  
  14.   
  15.   component: any;  
  16.   subscription: Subscription;  
  17.   registerResult: number = 0;  
  18.   registerUserData = new User();  
  19.   constructor(private _authservice: AuthService, private router: Router) {    
  20.     // redirect to home if already logged in  
  21.       if (this._authservice.currentUserValue) {   
  22.         this.router.navigate(['/paidevents']);  
  23.     }  
  24.   }  
  25.   
  26.   ngOnInit(): void {  
  27.     this.registerUserData.username   
  28.       = this.registerUserData.firstName   
  29.       = this.registerUserData.lastName   
  30.       = this.registerUserData.password   
  31.       = ""  
  32.   }  
  33.   
  34.   Register(user){  
  35.     console.log(user);  
  36.     this._authservice.registerUser(user).subscribe(data=>  
  37.       {  
  38.         console.log("login Details:", data);  
  39.         this.router.navigate(['/login'], { queryParams: { }});  
  40.       },  
  41.       error => {  
  42.         console.log("Error: ", error);  
  43.       },  
  44.       ()=>{  
  45.         console.log("login process complete!");  
  46.       });  
  47.     console.log('Logged in!');  
  48.   }  

Open register.component.html and add the below contents,
  1. <div class="row pt-5">  
  2.     <div class="co-md-6 mx-auto">  
  3.         <div class="card rounded-0">  
  4.             <div class="card-header">  
  5.                 <h3 class="mb-0">Register</h3>  
  6.             </div>  
  7.             <div class="card-body">  
  8.                 <form class="form" #newUserForm="ngForm" (ngSubmit)="Register(newUserForm.value)">  
  9.                     <div class="form-group">  
  10.                         <label for="">Username</label>  
  11.                         <input [(ngModel)]="registerUserData.username" name="username" type="text" class="form-control rounded-0" required>  
  12.                     </div>  
  13.                     <div class="form-group">  
  14.                         <label for="">First Name</label>  
  15.                         <input [(ngModel)]="registerUserData.firstName" name="firstName" type="text" class="form-control rounded-0" required>  
  16.                     </div>  
  17.                     <div class="form-group">  
  18.                         <label for="">Last Name</label>  
  19.                         <input [(ngModel)]="registerUserData.lastName" name="lastName" type="text" class="form-control rounded-0" required>  
  20.                     </div>  
  21.                     <div class="form-group">  
  22.                         <label for="">Password</label>  
  23.                         <input [(ngModel)]="registerUserData.password" name="password" type="password" class="form-control rounded-0" required>  
  24.                     </div>                      
  25.                     <a routerLink="/login" class="btn btn-primary float-left">Login</a>  
  26.                     <button type="submit" class="btn btn-primary float-right">Register</button>     
  27.                 </form>  
  28.             </div>  
  29.         </div>  
  30.     </div>  
  31. </div> 
Open events.component.ts and add the below contents,
  1. import { Component, OnInit } from '@angular/core';  
  2. import { EventService } from '../_services/event.service';  
  3.   
  4. @Component({  
  5.   selector: 'app-events',  
  6.   templateUrl: './events.component.html',  
  7.   styleUrls: ['./events.component.css']  
  8. })  
  9. export class EventsComponent implements OnInit {  
  10.   
  11.   public events: any[];   
  12.   constructor(private _eventService: EventService) { }  
  13.   
  14.   getAllEvents(){  
  15.     this._eventService.getEvents().subscribe(    
  16.       data => this.events = data,    
  17.       error => console.log('Error in getting event list ', error),    
  18.         () => {console.log('success to get event list...');    
  19.       });   
  20.   }  
  21.   ngOnInit(): void {  
  22.     this.getAllEvents();  
  23.   }  

Open events.component.html and add the below contents,
  1. <h2>Events Details:</h2>      
  2. <table class="table">    
  3.     <thead>    
  4.         <tr><th>Id</th><th>Name</th><th>Place</th><th>Date</th></tr>    
  5.     </thead>    
  6.     <tbody>    
  7.         <tr *ngFor="let event of events, index as i">    
  8.             <td>{{event.id}}</td>  
  9.             <td>{{event.name}}</td>  
  10.             <td>{{event.place}}</td>  
  11.             <td>{{event.date}}</td>  
  12.         </tr>    
  13.     </tbody>       
  14. </table>  
Open paid-events.component.ts and add the below contents,
  1. import { Component, OnInit } from '@angular/core';  
  2. import { AuthService } from '../_services/auth.service';  
  3. import { EventService } from '../_services/event.service';  
  4.   
  5. @Component({  
  6.   selector: 'app-paid-events',  
  7.   templateUrl: './paid-events.component.html',  
  8.   styleUrls: ['./paid-events.component.css']  
  9. })  
  10. export class PaidEventsComponent implements OnInit {  
  11.   
  12.   public events: any[];   
  13.   constructor(private _eventService: EventService) { }  
  14.   
  15.   getAllEvents(){  
  16.     this._eventService.getPaidEvents().subscribe(    
  17.       data => this.events = data,    
  18.       error => console.log('Error in getting event list'),    
  19.         () => {console.log('success to get event list...');    
  20.       });   
  21.   }  
  22.   
  23.   ngOnInit(): void {  
  24.     this.getAllEvents();  
  25.   }  

Open paid-events.component.html and add the below contents,
  1. <header></header>  
  2. <hr>  
  3. <table class="table">    
  4.     <thead>    
  5.         <tr><th>Id</th><th>Name</th><th>Place</th><th>Date</th></tr>    
  6.     </thead>    
  7.     <tbody>    
  8.         <tr *ngFor="let event of events, index as i">    
  9.             <td>{{event.id}}</td>  
  10.             <td>{{event.name}}</td>  
  11.             <td>{{event.place}}</td>  
  12.             <td>{{event.date}}</td>  
  13.         </tr>    
  14.     </tbody>       
  15. </table>  
Open app.module.ts and be sure that it contains the below contents,
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { FormsModule } from '@angular/forms';  
  4. import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';  
  5. import { AppRoutingModule } from './app-routing.module';  
  6. import { AppComponent } from './app.component';  
  7. import { RegisterComponent } from './register/register.component';  
  8. import { LoginComponent } from './login/login.component';  
  9. import { EventsComponent } from './events/events.component';  
  10. import { PaidEventsComponent } from './paid-events/paid-events.component';  
  11. import { fakeBackendProvider } from './_helpers/fake-backend-intercepter.provider';  
  12. import { JwtInterceptor } from './_helpers/jwt.interceptor';  
  13. import { ErrorInterceptor } from './_helpers/error.interceptor';  
  14. import { BrowserAnimationsModule } from '@angular/platform-browser/animations';  
  15. import { NgbModule } from '@ng-bootstrap/ng-bootstrap';  
  16.   
  17. @NgModule({  
  18.   declarations: [  
  19.     AppComponent,  
  20.     RegisterComponent,  
  21.     LoginComponent,  
  22.     EventsComponent,  
  23.     PaidEventsComponent  
  24.   ],  
  25.   imports: [  
  26.     BrowserModule,  
  27.     FormsModule,  
  28.     HttpClientModule,  
  29.     AppRoutingModule,  
  30.     BrowserAnimationsModule,  
  31.     NgbModule  
  32.   ],  
  33.   providers: [  
  34.     { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },  
  35.     { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },  
  36.     fakeBackendProvider  
  37.   ],  
  38.   bootstrap: [AppComponent]  
  39. })  
  40. export class AppModule { } 
Open app.component.ts and add the below contents,
  1. import { Component } from '@angular/core';  
  2. import { AuthService } from './_services/auth.service';  
  3. import { Router } from '@angular/router';  
  4.   
  5. @Component({  
  6.   selector: 'app-root',  
  7.   templateUrl: './app.component.html',  
  8.   styleUrls: ['./app.component.css']  
  9. })  
  10. export class AppComponent {  
  11.   constructor(private _authservice: AuthService, private router: Router){  
  12.     console.log(_authservice);  
  13.   }  
  14.   
  15.   isLoggedIn(){  
  16.     return this._authservice.currentUserValue;  
  17.   }  
  18.   
  19.   logout()  
  20.   {  
  21.     this._authservice.logout();  
  22.     this.router.navigate(['/login']);  
  23.   }  
  24.   
  25.   title = 'AuthApp';  

Open app.component.html and add the below contents,
  1. <nav class="navbar navbar-expand-lg navbar-dark bg-dark">  
  2.   <a class="navbar-brand" href="#">EMS</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" id="navbarSupportedContent">  
  8.     <ul class="navbar-nav mr-auto">  
  9.       <li class="nav-item active">  
  10.         <a class="nav-link" routerLink="/events" routerLinkActive="active">Events<span class="sr-only">(current)</span></a>  
  11.       </li>  
  12.       <li class="nav-item" *ngIf="isLoggedIn()">  
  13.         <a class="nav-link" routerLink="/paidevents" routerLinkActive="active">Members</a>  
  14.       </li>  
  15.       <li class="nav-item" *ngIf="!isLoggedIn()">  
  16.         <a class="nav-link" routerLink="/login" routerLinkActive="active">Login</a>  
  17.       </li>  
  18.       <li class="nav-item" *ngIf="!isLoggedIn()">  
  19.         <a class="nav-link" routerLink="/register" routerLinkActive="active">Register</a>  
  20.       </li>  
  21.       <li class="nav-item" *ngIf="isLoggedIn()" (click)="logout()">  
  22.         <a class="nav-link" routerLink="/register" routerLinkActive="active">Logout</a>  
  23.       </li>  
  24.     </ul>  
  25.   </div>  
  26. </nav>  
  27. <div class="container">  
  28.   <router-outlet></router-outlet>  
  29. </div> 
Your directory structure will be as below,
 
Interceptor In Angular
 
 
Run the application
 
 
Login with the register user (By default one user is already there user: ‘admin’ password : ‘1’)
 
 
Successful logged in user will be able to see the page Members (paid-event), otherwise Events page will be visible to all.
 
Click on Events menu
 
 
Click on Logout and you will be redirect to Login page.
 
Click on Register to register user,
 
 
 
We can see the Member menu only appears to the logged in user with the help of AuthGuard. You can check canActivate in app-routing.module.ts.
 
While working you can check the fake-backend-service provider to check for the HttpRequest for handling routes, Authenticate user, GetEvents/GetPaidEvents and other methods.
 
Interceptor jwt.interceptor is used to check the HttpRequest and will authenticate the user and handle the request with the logged in user with proper data and token information.
 
Error Interceptor will handle the request, catch the error and will be used to redirect and other operations that need to be performed.
 
Thank you.