30. Using Interceptors for Request Modification
HTTP Interceptors are a powerful Angular feature that allows you to intercept outgoing HTTP requests and incoming responses. They are ideal for cross-cutting concerns like authentication, logging, caching, or modifying headers.
1. Creating a Custom Interceptor
A custom interceptor class must implement the HttpInterceptor interface and its intercept() method.
Example: Adding an Authorization Token
typescript // auth-interceptor.ts 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
// 2. Clone the request and add the authorization header
const authReq = req.clone({
headers: req.headers.set('Authorization', `Bearer ${authToken}`)
});
// 3. Pass the cloned request to the next handler
return next.handle(authReq);
} }
2. Registering the Interceptor
Interceptors must be provided at the application root level using a special configuration in AppModule.
typescript // app.module.ts import { HTTP_INTERCEPTORS } from '@angular/common/http'; import { AuthInterceptor } from './auth-interceptor';
@NgModule({ // ... imports and declarations providers: [ // Register the interceptor using the multi: true flag { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true } ], // ... }) export class AppModule { }
Angular now runs AuthInterceptor for every single HTTP request before sending it to the backend.