0

嗨,我有一个服务 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);
      }
    })

  }
4

1 回答 1

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');
                }
            );

      } 
于 2017-11-09T11:44:12.050 回答