angular interceptor
What is Angular Interceptor?
Angular Interceptors are a powerful feature of Angular that allow you to intercept HTTP requests and responses. They provide a way to modify requests and responses, add custom headers, handle errors, or perform other operations based on the request or response.
How to create an Angular Interceptor?
To create an Angular Interceptor, you need to create a class that implements the HttpInterceptor
interface. The interface requires you to implement a single method called intercept
, which takes two arguments: a HttpRequest
object and a HttpHandler
object.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
@Injectable()
export class CustomInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
// your code here
return next.handle(req);
}
}
You can add your custom logic inside the intercept
method. If you want to pass the request to the next interceptor or to the HttpClient, you need to call the next.handle(req)
method.
How to use an Angular Interceptor?
To use an Angular Interceptor, you need to add it to the providers array in your module. You can do this in the @NgModule
decorator of your module:
@NgModule({
declarations: [ ... ],
imports: [ ... ],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: CustomInterceptor,
multi: true
}
],
bootstrap: [ ... ]
})
export class AppModule { }
In the above example, we added the CustomInterceptor
to the providers array using the HTTP_INTERCEPTORS
token. We set the multi
property to true
because we want to add multiple interceptors.
Multiple Interceptors in Angular
You can add multiple interceptors in Angular. Angular will call each interceptor in the order they are defined in the providers array. You can also define the order of your interceptors by setting a provide
property on them:
@Injectable({
providedIn: 'root',
provide: HTTP_INTERCEPTORS,
useClass: CustomInterceptor,
multi: true
})
export class CustomInterceptor1 implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
// your code here
return next.handle(req);
}
}
@Injectable({
providedIn: 'root',
provide: HTTP_INTERCEPTORS,
useClass: CustomInterceptor2,
multi: true
})
export class CustomInterceptor2 implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
// your code here
return next.handle(req);
}
}
In the above example, we added two interceptors to the providers array with the same HTTP_INTERCEPTORS
token but different provide
properties. Angular will call CustomInterceptor1
before CustomInterceptor2
.
Angular Interceptors are a powerful feature that makes it easy to handle HTTP requests and responses in your Angular application. They are easy to use and can save you a lot of time and effort.