HTTP Interceptors
Imagine you need to add an authentication token to every outgoing request, or log every request for debugging. Doing this manually in each service call would be repetitive. Interceptors are a powerful feature that lets you intercept HTTP requests and responses globally to apply common logic.
Interceptors are classes that implement
HttpInterceptor interface. They can modify requests, handle responses, or even short-circuit requests (like serving from cache).Creating an Interceptor
Generate an interceptor using CLI:
ng generate interceptor auth
# or shorthand
ng g interceptor auth
Implement the interceptor:
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> {
// Clone the request and add the authorization header
const token = localStorage.getItem('token');
const authReq = req.clone({
headers: req.headers.set('Authorization', `Bearer ${token}`)
});
// Pass the cloned request instead of the original
return next.handle(authReq);
}
}
Providing the Interceptor
Interceptors must be provided in your module using the
HTTP_INTERCEPTORS multi-provider token.import { HTTP_INTERCEPTORS } from '@angular/common/http';
@NgModule({
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
]
})
export class AppModule { }
Multiple Interceptors
You can have multiple interceptors. They are called in the order you provide them.
Logging Interceptor Example
Another common use is logging all requests and responses.
import { tap } from 'rxjs/operators';
intercept(req: HttpRequest, next: HttpHandler) {
console.log('Outgoing request:', req);
const start = Date.now();
return next.handle(req).pipe(
tap(
event => {
if (event instanceof HttpResponse) {
console.log('Request took:', Date.now() - start, 'ms');
}
},
error => console.error('Request error:', error)
)
);
}
Two Minute Drill
- Interceptors globally handle HTTP requests/responses.
- Implement HttpInterceptor and override intercept method.
- Clone requests to modify headers or body.
- Provide interceptors using HTTP_INTERCEPTORS with multi:true.
- Use interceptors for auth, logging, caching, error handling.
Need more clarification?
Drop us an email at career@quipoinfotech.com
