0 day streak
javascript / intermediate
Snippet

Functional HTTP Interceptors

Functional interceptors provide a concise way to intercept and modify HTTP requests globally using the inject function instead of class-based providers.

snippet.js
javascript
1
2
3
4
5
6
7
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const authService = inject(AuthService);
const authReq = req.clone({
setHeaders: { Authorization: `Bearer ${authService.getToken()}` }
});
return next(authReq);
};
angular
Breakdown
1
HttpInterceptorFn
Type definition for modern functional interceptors in Angular.
2
inject(AuthService)
Retrieves the authentication service directly within the function scope.
3
req.clone()
Creates a copy of the immutable request to modify headers safely.