javascript / intermediate
Snippet
Functional Interceptors in Angular
Functional interceptors are a modern, lightweight way to handle HTTP requests and responses globally, replacing the older class-based approach.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
import { HttpInterceptorFn } from '@angular/common/http';export const authInterceptor: HttpInterceptorFn = (req, next) => {const authToken = 'your-token-here';const authReq = req.clone({setHeaders: {Authorization: `Bearer ${authToken}`}});return next(authReq);};
angular
Breakdown
1
const authInterceptor: HttpInterceptorFn
Defines the interceptor as a function instead of a class.
2
req.clone({...})
HTTP requests are immutable; we must clone them to modify headers.
3
return next(authReq);
Passes the modified request to the next handler in the chain.