In this blog post, I will show you how and when to use the angular HTTP INTERCETPR
in Angular Application.
What is Angular HttpInterceptor
Http Interceptor is angular framework feature which allows the angular application to intercept and modify the Http request before sending it to server.
When to use the Angular Http Interceptor
You can use the HTTP interceptor in the following cases
- Modify the headers of HTTP request like adding the authorization header
- Profiling/Tracing all the application at a central place
- Global exception handling
- Adding retry logic for the failed request
There are other uses cases also, but above use cases are fit for almost every angular application.
How to create custom HTTP interceptor in Angular
Creating custom HTTP interceptor is very simple in Angular. Just create a class and implements the HttpInterceptor
which have one method which signature is shown below.
interface HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
}
How and where to register the custom HTTP interceptor
After implementing the HTTP interceptor, you have to register the interceptor in the angular pipeline
You can register the HTTP interceptor in the module as below
@NgModule({
imports: [BrowserModule, FormsModule, HttpClientModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
providers: [
{
provide HTTP_INTERCEPTORS,
useClass: CustomInterceptor,
multi: true
}
]
})
export class AppModule {}
- The
provide
property holds the token that serves as the key for both locating a dependency value and configuring the injector. - The second property is a provider definition object, which tells the injector how to create the dependency value.
Does HTTP interceptor order matters
Yes, HTTP interceptor executes in order.
DEMO