Problem Statement
What are HTTP interceptors and common use cases?
Explanation
Interceptors sit between your app and HttpClient. They can add auth headers, log traffic, retry requests, or centralize error handling. They’re registered as multi providers for HTTP_INTERCEPTORS.
Code Solution
SolutionRead Only
export class TokenInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler){
const token = localStorage.getItem('token');
const auth = token ? req.clone({ setHeaders:{ Authorization:`Bearer ${token}` }}) : req;
return next.handle(auth);
}
}Practice Sets
This question appears in the following practice sets: