HTTP Interceptors intercept HTTP requests/responses, letting you modify them, log them, or handle errors.
typescript
// auth.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
// Add auth token to request
const token = localStorage.getItem('auth_token');
if (token) {
req = req.clone({
setHeaders: {
Authorization: `Bearer ${token}`
}
});
}
return next.handle(req);
}
}
// logging.interceptor.ts
export class LoggingInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
console.log('Request:', req.url);
const started = Date.now();
return next.handle(req).pipe(
tap(() => {
const elapsed = Date.now() - started;
console.log(`Response took ${elapsed}ms`);
})
);
}
}
// app.module.ts
@NgModule({
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: LoggingInterceptor, multi: true }
]
})You should see
(Every HTTP request passes through the interceptors, which can handle things like auto-adding tokens and logging)