Interceptors
Interceptors are a powerful tool provided by Angular. They form an essential part of Angular's Http
module and are used to inspect and transform HTTP requests from your application to the server, and HTTP responses from the server to your application.
Why use Interceptors?
Interceptors can be used to perform a variety of operations, such as:
- Adding a token or some specific header to all outgoing HTTP requests.
- Handling responses and errors globally.
- Caching HTTP requests and responses.
- Transforming the request or the response.
Implementing an Interceptor
Let’s jump in and create a simple interceptor. Angular interceptors are simply services that implement the HttpInterceptor
interface.
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
export class MyInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
// This is where you can perform the desired actions on the request.
return next.handle(req);
}
}
In the intercept
method, you have access to the HttpRequest
and the HttpHandler
. The HttpHandler
is a next-in-chain interceptor, which means you can pass the request to the next interceptor by calling next.handle(req)
.
Modifying HTTP Requests
One common use of interceptors is to modify HTTP requests, for example, to add an authentication token to all requests.
intercept(req: HttpRequest<any>, next: HttpHandler) {
const modifiedReq = req.clone({
headers: req.headers.set('Authorization', 'Bearer ' + 'your-token'),
});
return next.handle(modifiedReq);
}
Handling HTTP Responses
You can also use interceptors to handle HTTP responses. This is useful if you want to display a notification or log something when a request is successful.
intercept(req: HttpRequest<any>, next: HttpHandler) {
return next.handle(req).pipe(
tap(() => console.log('Request was successful'))
);
}
Handling Errors
Interceptors can be used to handle errors as well. This is useful if you want to display a notification or log something when a request fails.
intercept(req: HttpRequest<any>, next: HttpHandler) {
return next.handle(req).pipe(
catchError(error => {
// Handle the error
return throwError(error);
})
);
}
Providing the Interceptor
The last step is to provide the interceptor in your app.module.ts
.
@NgModule({
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true }
]
})
export class AppModule { }
The multi: true
option is necessary because you might want to provide more than one interceptor.
Conclusion
Angular Interceptors can be a powerful way to control and manipulate HTTP requests and responses. They provide a centralized place to handle different aspects of HTTP communications, which can make your code cleaner and easier to maintain.