Functional Interceptor in Angular: What It Is and How It Works
functional interceptor in Angular is a simple function that intercepts HTTP requests and responses to modify or handle them before they reach the server or the app. It works like a middleware that can add headers, log data, or handle errors without creating a class, making it lightweight and easy to use.How It Works
Think of a functional interceptor as a checkpoint on a road where every HTTP request and response must pass through. At this checkpoint, you can inspect, change, or log the traffic before it continues. Instead of writing a full class, Angular lets you write a simple function that acts as this checkpoint.
This function receives the outgoing request and a handler to continue the process. You can modify the request, then pass it along. When the response comes back, you can also inspect or change it before your app uses it. This makes it easy to add common features like authentication tokens or error handling in one place.
Example
import { HttpEvent, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http'; import { Observable, tap } from 'rxjs'; export function customHeaderInterceptor(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const modifiedReq = req.clone({ setHeaders: { 'X-Custom-Header': 'MyHeaderValue' } }); return next.handle(modifiedReq).pipe( tap(event => { if (event instanceof HttpResponse) { console.log('Response status:', event.status); } }) ); }
When to Use
Use functional interceptors when you want a simple, clear way to modify HTTP requests or responses without the overhead of creating a class. They are great for adding headers like authentication tokens, logging requests and responses, or handling errors globally.
For example, if your app needs to add a token to every request or show a loading spinner during HTTP calls, a functional interceptor can do this cleanly and efficiently.
Key Points
- Functional interceptors are simple functions that intercept HTTP requests and responses.
- They replace the need for class-based interceptors for simpler use cases.
- They help add headers, log data, or handle errors globally.
- They keep your code lightweight and easy to maintain.