6

What Is Angular HttpInterceptor?

HttpInterceptor - HttpInterceptors is an interface which uses to implement the intercept method.
Intercepts HttpRequest and handles them.

Intercepts is an advanced feature that allows us to intercept each request/response and modify it before sending/receiving.

Interceptors capture every request and manipulate it before sending and also catch every response and process it before completing the call.

Firstly, we can implement own interceptor service and this service will “catch” each request and append an Authorization header.

You can see in the following example,
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  //Intercepts HttpRequest and handles them.
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const reqHeader = req.clone({headers: req.headers.set('Authorization', 'MyAuthToken')});

    return next.handle(reqHeader);
  }
}

After that you can configure your own interceptor service (MyInterceptor) and HTTP_INTERCEPTORS in the app Module.
import {NgModule} from '@angular/core';
import {HTTP_INTERCEPTORS} from '@angular/common/http';

@NgModule({
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: MyInterceptor,
    multi: true,
  }],
})
export class AppModule {}


Following this logic, Authorization token will be appended to each request. It’s also possible to override request’s headers by using set() method.


For more detail kindly refer the link.... 
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.
^