Advanced HTTP Interceptors in Angular
Introduction
HTTP Interceptors are a powerful feature in Angular that allow you to intercept and modify HTTP requests and responses. This can be useful for a variety of purposes, such as logging, modifying headers, or handling errors centrally.
What are Interceptors?
Interceptors are classes that implement the HttpInterceptor
interface. They allow you to hook into the HTTP request/response lifecycle in Angular applications.
Key Points:
- Interceptors can modify requests before they are sent.
- They can also transform responses before they reach the component.
- Multiple interceptors can be chained together.
Creating an Interceptor
To create an HTTP interceptor, follow these steps:
- Create a new interceptor class that implements
HttpInterceptor
. - Implement the
intercept
method. - Register the interceptor in the
AppModule
.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const clonedRequest = req.clone({
setHeaders: {
Authorization: `Bearer YOUR_TOKEN_HERE`
}
});
return next.handle(clonedRequest);
}
}
Finally, register your interceptor in the AppModule
:
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthInterceptor } from './auth.interceptor';
@NgModule({
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
]
})
export class AppModule { }
Common Use Cases
Interceptors can be used for:
- Adding authentication tokens to requests.
- Logging HTTP requests and responses.
- Handling global error responses.
- Retrying failed requests.
Best Practices
When using HTTP interceptors, consider the following best practices:
- Keep interceptors focused on a single responsibility.
- Avoid long-running operations in interceptors.
- Use observables to handle asynchronous operations.
- Test interceptors thoroughly to ensure correct behavior.
FAQ
Can I use multiple interceptors?
Yes, Angular allows you to register multiple interceptors, and they will be executed in the order they are provided.
What happens if an interceptor does not call next.handle()?
If an interceptor does not call next.handle()
, the request will not proceed, and the response will not be returned to the caller.
Can interceptors modify response data?
Yes, interceptors can modify the response data by transforming it before it is returned to the component.