What is Interceptor in Angular | Example

 Angular provides many built-in libraries to help scale out large applications. Interceptors are one of the built-in libraries for specifically handling HTTP requests and responses at a global app level.

it is a unique type of Angular Service that we can implement in Angular. HttpClient plays a major role. it modifies the app HTTP request globally before they send them back (Server).

What is Angular HTTP Interceptor

How to create the Interceptor in Angular

  • To implement an Interceptor in Angular, we need to create a class that’s injectable (Ex: AuthInterceptor )
  • The class should implement from the Interface HttpInterceptor.
  • The class should define an intercept method to correctly implement HttpInterceptor 
  • The intercept method takes the 2 main arguments, that are req and next, and returns an observable of type HttpEvent (Observable<HttpEvent<any>>)

Example Task below code going to check the Authorization and check the user is a valid user or not if the valid user then Authorize the Page if not redirect to the login page.



import { HttpInterceptorHttpRequestHttpHandlerHttpEvent } 
from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { Router } from '@angular/router';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

    constructor(private routerRouter) {

    }

    intercept(reqHttpRequest<any>, nextHttpHandler): Observable<HttpEvent<any>> {
        // tslint:disable-next-line:no-debugger
        debugger;
        if (localStorage.getItem('token') != null) {
            const clonedReq = req.clone({
                headers: req.headers.set('Authorization''Bearer ' + localStorage.getItem('token'))
            });
            return next.handle(clonedReq).pipe(
                tap(
                    succ => { },
                    err => {
                        if (err.status === 401) {
                            localStorage.removeItem('token');
                            this.router.navigateByUrl('/user/login');
                        } else if (err.status === 403) {
                            this.router.navigateByUrl('/forbidden');
                        }
                    }
                )
            );
        } else {
            return next.handle(req.clone());
        }
    }
}


The above code returns the Observable :

  • req is the request object (it is the type of HttpRequest).
  • next is the HTTP handler, (it is a type of HttpHandler).
To Achieve the Interceptor in Angular then we need to register it at Module as shown below



import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModuleHTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthInterceptor } from './auth/auth.interceptor';

@NgModule({
  declarations: [
   ],
  imports: [    
    HttpClientModule
  ],
  providers: [UserService , { provide: HTTP_INTERCEPTORS
useClass: AuthInterceptor,
     multi: true }],
 })
export class AppModule { }








Previous Post Next Post