我有一个服务AuthenticationService来刷新令牌和截取AuthHttp调用的拦截器,问题是在调用失败的拦截器方法中我使refreshToken调用订阅了observable然后当我得到我需要调用的响应时第一个http调用,并且无法使其工作:
refreshToken(): Observable<any>{
return this.authHttp.get(GLOBAL.apiurl+'/refresh-token',"").map(
(response) => {
let token = response.json() && response.json().token;
if (token){
console.log('refresh token');
localStorage.setItem('token', token);
return true;
}
else{
console.log('no token');
this.resetLocalStorage();
return false;
}
}
);
}
然后我有一个authttp的拦截器:
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
return this.intercept(super.request(url, options));
}
intercept(observable: Observable<Response>): Observable<Response> {
return observable.catch((err, source) => {
if (this.isUnauthorized(err.status)) {
//logout the user or do what you want
this.authService.refreshToken().subscribe(result => {
if(!result){
}
HERE THE FIRST FAILED CALL MUST BE CALLED
},
err => {
}
);
if (err instanceof Response) {
return Observable.throw(err.json().message || 'backend server error');
}
return Observable.empty();
} else {
return Observable.throw(err);
}
})
}
答案 0 :(得分:0)
在此块中,您将返回Observable.empty();在异步调用之外,我认为你需要在服务调用中分配这个。我想现在你将获得空的返回,因为你已经返回了observable而没有等待服务调用(下面给出了你可能需要根据你的要求纠正它的伪代码)
if (this.isUnauthorized(err.status)) {
//logout the user or do what you want
this.authService.refreshToken().subscribe(result => {
if(!result){
}
HERE THE FIRST FAILED CALL MUST BE CALLED
// your return must be somewhere here
return Observable.empty();
},
err => {
return Observable.throw(err.json().message || 'backend server error');
}
);
}