Problem Statement
How do you attach an auth token to all requests and refresh it on 401?
Explanation
In an interceptor, clone requests with Authorization header from storage. On 401, queue requests and refresh the token once; replay queued requests with the new token. Prevent refresh loops and ensure thread-safety with a shared subject/flag.
Code Solution
SolutionRead Only
intercept(req: HttpRequest<any>, next: HttpHandler){
const token = this.auth.token();
const authReq = token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` }}) : req;
return next.handle(authReq).pipe(catchError(err => this.auth.handle401(err, authReq, next)));
}