What is interceptor and how can implement it in angular?

Priti Jha
2 min readFeb 10, 2023

--

In Angular, an interceptor is a mechanism that allows you to modify or transform HTTP requests and responses before they are sent to the server or processed by the client. It’s a powerful feature that provides a way to handle common tasks, such as adding headers, handling errors, or logging requests, in a centralized and reusable way.

Here’s how you can implement an interceptor in Angular:

Create an injectable service that implements the HttpInterceptor interface:

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

@Injectable()
export class MyInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Add logic to modify the request or handle the response here
return next.handle(req);
}
}

Register the interceptor in the root module by adding it to the providers array and importing the HTTP_INTERCEPTORS symbol:

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { MyInterceptor } from './my-interceptor.service';

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

Modify the request or handle the response in the intercept method of the interceptor service. For example, you can add a header to every request:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const modifiedReq = req.clone({
headers: req.headers.set('My-Header', 'my header value')
});
return next.handle(modifiedReq);
}

That’s it! Your interceptor is now registered and active. You can use it to perform any logic you need on HTTP requests and responses, such as error handling, logging, or adding headers.

Note that you can also implement multiple interceptors, and the order in which they are applied is determined by the order in which they are registered in the providers array.

--

--

Priti Jha
Priti Jha

Written by Priti Jha

Senior front-end developer writing about Angular 8 , Ionic Framework ,Javascript, HTML, Css and all front end technology.