Interceptors - An Important Feature Of HTTP Client

In this article, we will learn about Interceptors, one of the important and useful features of HTTP Client.

What are Interceptors?

Interceptors check each and every incoming and outgoing request to the server and are also able to manipulate them before actually sending to the server.

Imagine the use case where we need to send the user authentication token each and every time with the HTTP request we are sending to the server. So, instead of writing/fetching the token in every request, we can simply create the interceptors, which will inspect our HTTP request, manipulate it (add auth token), and then actually pass it to the server.

In another use case, we need to pass the headers with each and every HTTP request, so instead of passing it to every request, we can create interceptors which inspects our request, manipulates it with headers, and passes it to the server.

In the same way, interceptors can also be used when we receive the data from the server. So, before passing the actual data to the component, an interceptor can also be used to manipulate the data.

Without interceptors, we would have to implement all the tasks explicitly for each HTTP Client method.

Intercepting Request

Creating an interceptor is very simple; just declare a class that implements the intercept () method of the HttpInterceptor Interface, which can be imported from @angular/common/http. Below is the code snippet of newly created Interceptor.

  1. import {  
  2.     HttpInterceptor,  
  3.     HttpRequest,  
  4.     HttpHandler,  
  5.     HttpEvent  
  6. } from "@angular/common/http";  
  7. import {  
  8.     Observable  
  9. } from "rxjs";  
  10. export class interceptorclass implements HttpInterceptor {  
  11.     intercept(req: HttpRequest < any > , next: HttpHandler): Observable < HttpEvent < any >> {  
  12.         console.log(httpreq);  
  13.         return next.handle(httpreq);  
  14.     }  
  15. }  

Intercept method will take 2 arguments.

  • HttpRequest
  • HttpHandler

HttpRequest

It is the actual request which we are making through over services or component. These requests are always immutable so it can not be edited directly.

  1. req.url = req.url.replace('http://''https://'); this will not work directly because it is readonly.  

To make it work, we first need to clone the request and then we can make changes on cloned request only. Below is the code snippet for cloned URL by interceptors.

  1. intercept(req: HttpRequest < any > , next: HttpHandler): Observable < HttpEvent < any >> {  
  2.     const httpreq = req.clone({  
  3.         url: req.url.replace('http://''https://');  
  4.     });  
  5.     console.log(httpreq);  
  6.     return next.handle(httpreq);  
  7. }  

HttpHandler

In most of the cases, Interceptors will call.

  1. next.handle(httprequest-object);  

Which will call the next handler in the chain or eventually the back-end handler. An interceptor skips calling next.handle() and can also return its own Observable.

By only just defining interceptors will do nothing. In order to make an interceptor work, we must provide the interceptors in the app.module.ts file as shown below.

Providing Interceptors

  1. import {  
  2.     BrowserModule  
  3. } from '@angular/platform-browser';  
  4. import {  
  5.     NgModule  
  6. } from '@angular/core';  
  7. import {  
  8.     HttpClientModule,  
  9.     HTTP_INTERCEPTORS  
  10. } from '@angular/common/http';  
  11. import {  
  12.     AppComponent  
  13. } from './app.component';  
  14. import {  
  15.     intercepterclass  
  16. } from './intercepterclass';  
  17. @NgModule({  
  18.     declarations: [  
  19.         AppComponent  
  20.     ],  
  21.     imports: [  
  22.         BrowserModule,  
  23.         HttpClientModule  
  24.     ],  
  25.     providers: [{  
  26.         provide: HTTP_INTERCEPTORS,  
  27.         useClass: interceptorclass,  
  28.         multi: true  
  29.     }],  
  30.     bootstrap: [AppComponent]  
  31. })  
  32. export class AppModule {}  

Note
By providing Multi: true, means we can allow multiple interceptors.

So now, to check out if the interceptor is working or not, I will make an HTTP Request through my app.component.ts, which, in turn, calls to our task.service.ts which will call the interceptorclass. Below is the code snippet of app.component.ts and task.service.ts files respectively.

  1. import {  
  2.     TaskService  
  3. } from './task.service';  
  4. import {  
  5.     Component,  
  6.     OnInit  
  7. } from '@angular/core';  
  8. import {  
  9.     Task  
  10. } from './task';  
  11. @Component({  
  12.     selector: 'app-root',  
  13.     templateUrl: './app.component.html',  
  14.     styleUrls: ['./app.component.css']  
  15. })  
  16. export class AppComponent implements OnInit {  
  17.     title = 'httpclientDemo';  
  18.     ngOnInit() {  
  19.         this._taskdata.getAllTask().subscribe(  
  20.             (data) => {  
  21.                 console.log("selected" + data);  
  22.             });  
  23.     }  
  24. }  

Task.service.ts

  1. import {  
  2.     Task  
  3. } from './task';  
  4. import {  
  5.     Injectable  
  6. } from '@angular/core';  
  7. import {  
  8.     HttpClient  
  9. } from '@angular/common/http';  
  10. @Injectable({  
  11.     providedIn: 'root'  
  12. })  
  13. export class TaskService {  
  14.     url: string = 'http://rkdemotask.herokuapp.com/tasks/';  
  15.     constructor(public _http: HttpClient) {}  
  16.     getAllTask() {  
  17.         return this._http.get < Task > (this.url);  
  18.     }  
  19. }  

So, as you can see from the above code snippet, we are making a call to http:// , but this call will go through our interceptors which will eventually replace http:// with https://.

Interceptors - An Important Feature Of HTTP Client 

In the same way, we can use Interceptors to add headers. The code of the interceptors is shown below.

  1. import {  
  2.     HttpInterceptor,  
  3.     HttpRequest,  
  4.     HttpHandler,  
  5.     HttpEvent  
  6. } from "@angular/common/http";  
  7. import {  
  8.     Observable  
  9. } from "rxjs";  
  10. export class intercepterclass implements HttpInterceptor {  
  11.     intercept(req: HttpRequest < any > , next: HttpHandler): Observable < HttpEvent < any >> {  
  12.         const httpreq = req.clone({  
  13.             url: req.url.replace('http://''https://'),  
  14.             headers: req.headers.set('Content-Type''application/json')  
  15.         });  
  16.         console.log(httpreq);  
  17.         return next.handle(httpreq);  
  18.     }  
  19. }  
 Interceptors - An Important Feature Of HTTP Client

I hope this will be helpful to you in understanding Interceptors.

Thank you for reading.