Showing posts with label Angular Interceptors. Show all posts
Showing posts with label Angular Interceptors. Show all posts

Wednesday 9 January 2019

Angular interceptors sample code

Angular Interceptors : 

Interceptors  generally used to modify the request before sending the request to the server and modifying the response after receiving the response from the server before passing to the application code .

Here is the sample code for angular interceptors :


DemoInterceptor.ts 

import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';

@Injectable()
export class DemoInterceptor implements HttpInterceptor
{
    intercept(req : HttpRequest<any>,next : HttpHandler) : Observable<HttpEvent<any>>
    {
        let request  : HttpRequest<any> = req.clone({
         setHeaders :
         {
             "Authorization" : "customtoken"
         }
        });
        return next.handle(request);
    }
}

Once the above code snippet is used then , we need to configure the interceptor in the app.module.ts
providers sections  like below  :

app.module.ts  : 

 providers: [
             {
               provide : HTTP_INTERCEPTORS , useClass : DemoInterceptor,multi:true
            }

  ]


After these configurations we can see the request headers for all request contains the "Authorization" in the request header: