Angular · Middle · Question 47 of 75
How do you add an auth header to every request?
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = inject(AuthService).token();
return next(token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req);
};
// provideHttpClient(withInterceptors([authInterceptor]))- ✓Correct answer: With a functional interceptor that clones the request - requests are immutable
- 2By assigning
req.headers.Authorizationdirectly in the interceptor - 3By adding the header in each component manually
Explanation
HttpRequest is immutable, so interceptors call clone. Interceptors run in the order they are listed and can also handle errors, retries, logging and caching.