我正在关注这个例子:https ://www.intertech.com/Blog/angular-4-tutorial-handling-refresh-token-with-new-httpinterceptor/
一切都很好,除了方法handle401Error
。它不会执行,除非我添加subscribe
拦截器。即使尝试遵循该示例,我也一定遗漏了一些东西。
以下是相关代码:
零件:
ngOnInit() {
this.service.getData()
.subscribe((response: any) => {
this.message = `Worked with status = ${response.status}`;
},
error => this.message = `Failed with status = ${error.status}`);
}
服务:
constructor(private http: HttpClient) {
this.currentToken = this.authTokenStale;
}
public authTokenStale: string = 'stale_auth_token';
public authTokenNew: string = 'new_auth_token';
public currentToken: string;
getData() {
return this.http.get<{status}>('https://private-4002d-testerrorresponses.apiary-mock.com/getDataError401');
}
getAuthToken() {
return this.currentToken;
}
refreshToken(): Observable<string> {
this.currentToken = this.authTokenNew;
return Observable.of(this.authTokenNew).delay(200);
}
拦截器:
isRefreshingToken: boolean = false;
tokenSubject: BehaviorSubject<string> = new BehaviorSubject<string>(null);
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('interceptor fired!')
let service = this.inj.get(Service);
// addToken() returns headers, getAuthToken() returns token
return next.handle(this.addToken(request, service.getAuthToken())).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// success
}
}, (err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
return this.handle401Error(request, next);
}
}
});
}
处理401错误:
handle401Error(req: HttpRequest<any>, next: HttpHandler) {
if (!this.isRefreshingToken) {
this.isRefreshingToken = true;
let service = this.inj.get(Service);
this.tokenSubject.next(null);
return service.refreshToken()
.switchMap((newToken: string) => {
console.log('goes to switchMap') // does not come here!
if (newToken) {
this.tokenSubject.next(newToken);
return next.handle(this.addToken(this.getNewRequest(req), newToken));
}
return this.logoutUser();
})
.catch(....)
//.subscribe(() => {) // only works!
.finally(() => {
console.log('goes to finally')
this.isRefreshingToken = false;
});
} else {
return this.tokenSubject
.filter(token => token != null)
.take(1)
.switchMap(token => {
return next.handle(this.addToken(this.getNewRequest(req), token));
});
}
}
抱歉,有一些代码,但我认为一切都与能够重现该问题有关。
我也做了一个
StackBlitz
展示问题!