4

我正在关注这个例子: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

展示问题!

4

2 回答 2

9

如果您使用 Angular 6,请记住 RxJS 库中的更改。在新的 RxJS 中,与do操作符一致

next.handle(req).do(() => {});

必须改为:

next.handle(req).pipe(tap(() => {}));

查看这篇文章了解更多信息:

  1. https://www.academind.com/learn/javascript/rxjs-6-what-c​​hanged/
  2. https://auth0.com/blog/whats-new-in-rxjs-6/
于 2018-06-20T10:32:43.670 回答
3

我通过将逻辑从https://stackoverflow.com/a/47420967/7741865error移到 acatch而解决了这个问题

return next.handle(authReq).catch((err: any) => { //<--if error use a catch
  if (err instanceof HttpErrorResponse) {
    if (err.status === 401) {
      //use switchMap to really return next.handle(authReq)
      return auth.refreshToken().switchMap((value: any) => {
        let httpHeaders = new HttpHeaders()
          .set('Content-Type', 'application/json; charset=utf-8')
          .set('Authorization', '' + auth.getAuthToken())
        const authReq = req.clone({ headers: httpHeaders });
        return next.handle(this.getNewRequest(req));
      })
    };
  }
  //Other case throw an error
  return Observable.throw(err);
});

StackBlitz

于 2017-11-24T07:11:09.940 回答