Problem Statement
What are HTTP interceptors and a common use case?
Explanation
Interceptors sit between your app and the server. They can read/alter outgoing requests and incoming responses. Common uses: add auth tokens, set headers, log traffic, retry, or handle errors globally. Register them with the `HTTP_INTERCEPTORS` multi provider.
Code Solution
SolutionRead Only
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler){
const token = localStorage.getItem('userToken');
const authReq = token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` }}) : req;
return next.handle(authReq);
}
}