In Angular, an interceptor is a way to intercept HTTP requests or responses before they are sent or received by the application. Interceptors allow you to modify the request or response, add custom headers, handle errors, or perform any other operations that are necessary for every HTTP call.
To create an interceptor in Angular, you typically follow these steps:
Create the Interceptor Class:
-
Create a new Angular service:
ng generate service interceptor
-
Implement the interceptor:
In the generated service file (
interceptor.service.ts
), implement theHttpInterceptor
interface and define theintercept method. This method intercepts HTTP requests and responses.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
, next: HttpHandler): Observable > { // Modify or handle the request here // For example, adding headers const modifiedReq = req.clone({ setHeaders: { 'Authorization': 'Bearer ', 'Content-Type': 'application/json' } }); // Pass the modified request to the next handler return next.handle(modifiedReq); } }
Register the Interceptor
-
Provide the interceptor:
In your Angular module (often
app.module.ts
), you need to provide the interceptor by adding it to theproviders
array and importing necessary modules.import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { MyInterceptor } from './interceptor.service'; @NgModule({ imports: [BrowserModule, HttpClientModule], providers: [ { provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true } ], bootstrap: [AppComponent] }) export class AppModule { }
Notes:
- The
HTTP_INTERCEPTORS
token is used to provide a list of interceptors. - Using
multi: true
allows multiple interceptors to be registered in the application. - Interceptors are often used for tasks like authentication, error handling, logging, etc.
Remember to adjust the interceptor's logic to suit your application's requirements.