我已经实现了令牌保存、检索和刷新的逻辑。问题在于当我拦截 HttpInterceptor 中的 403 错误时,同时发出的其他调用也会刷新令牌。我希望能够保留这些调用,直到我的令牌刷新完成。为此,我需要创建一个“信号量”来控制请求。
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
private auth: AuthService;
constructor(private injector: Injector) {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.auth = this.injector.get(AuthService);
if(this.auth.isAuthenticated()){
request = request.clone({
setHeaders: {
Accept: 'application/json',
Authorization: `Bearer ${localStorage.getItem('access_token')}`
}
});
} else {
request = request.clone({
setHeaders: {
Accept: 'application/json'
}
});
}
return next.handle(request).catch(error => {
if (error.status === 401) {
console.log('refreshing token');
// TODO: return Refresh Token here and hold other calls
}
return Observable.throw(error);
});
}
HttpInterceptor
代码吗? - Dmitry