How to create HTTP Interceptor in Angular 11

Every application needs to communicate with the backend server for data to show in UI, and for that, we mostly use either JSON or XML. But for backend communication, the REST API needs to be authorized based on Authorization & Authentication (Bearer token). 

Angular Interceptor helps to modify the HTTP request globally before they are sent to the server. Interceptors are a unique type of Angular Service that we can implement. Interceptors allow us to intercept incoming or outgoing HTTP requests using the HttpClient. By intercepting the HTTP request, we can modify or change the value of the request.

 

Interceptors is a unique type of Angular service that allow us to intercept incoming or outgoing HTTP request using HttpClient.

 

In this blog, we are going to discuss the following points - 

  • Setup and configure Interceptor
  • HTTP Request & Response
  • HTTP Error Handling

Setup And Configure Interceptor

First, create an Angular project, and import HTTPClientModule to the app.module.ts file. HTTP interceptor class can be created by extending HttpInterceptor. So let's create that one.

npm g service service/http-interceptor

It will create an http-interceptor service along with a unit test case file (http-interceptor.service.ts & http-interceptor.service.spec.ts). Update the file accordingly.

import { Injectable } from '@angular/core';

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

import { Observable } from 'rxjs';

 

@Injectable()

export class HttpInterceptorService implements HttpInterceptor {

constructor() { }

 

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

throw new Error('Method not implemented.');

}

}

 

 

Update the app.module.ts file as well. 

import { BrowserModule } from '@angular/platform-browser';

import { NgModule } from '@angular/core';

 

import { AppComponent } from './app.component';

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

import { DEFAULT_TIMEOUT, HttpInterceptorService } from './service/http-interceptor.service';

 

@NgModule({

declarations: [

AppComponent

],

imports: [

BrowserModule,

HttpClientModule

],

providers: [

{

provide: HTTP_INTERCEPTORS,

useClass: HttpInterceptorService,

multi: true

},

{ provide: DEFAULT_TIMEOUT, useValue: 60000 }

],

bootstrap: [AppComponent]

})

export class AppModule { }

 


HTTP Request & Response

So in the case of the HTTP request, you might have few requests are needed a custom HTTP Header like "Authorization" and a few do not require any header. In such cases, you can have an array that defines the list of URLs that does not need any header. 

export const apiWithoutHeader = [

endPoints.login.LOGIN_URL,

endPoints.utility.GET_COPYRIGHT_URL,

endPoints.utility.GET_SECRETS_URL,

endPoints.user.GENERATE_NEW_TOKEN_URL,

endPoints.user.FORGOT_PASSWORD_URL,

endPoints.user.RESET_PASSWORD_URL

];

 

Also, you can add a default timeout value for your API call. So once the expected time elapses, API will throw an error at the component, and you can handle it from there. 

export const DEFAULT_TIMEOUT = new InjectionToken<number>('defaultTimeout');

 

In case of Success response with HTTP code 200, you can send it to the component. But in the case of other HTTP error codes like 400 series, 500 series, etc you can handle it in your way. 

HTTP Error 400, 404, 403 - Notify component that API failed to get a response.  You can show a Toast message for that.

HTTP Error 401 - The access token has expired, you need to renew the token and call the same API once again with the renewed token.

HTTP Error 500 - Notify the component that API failed to get a response.  You can show a Toast message for that.

 


HTTP Interceptor Service

You can find the actual codebase from here.

If you have any questions or clarification please comments below.

Happy Coding!

- LP