角度刷新令牌拦截器,发送get调用并更新组件

时间:2019-09-18 10:03:12

标签: javascript angular typescript rxjs angular5

我正在尝试通过刷新令牌并重试请求来实现新的角度拦截器并处理401未经授权的错误。

我已经成功地缓存了失败的请求,并且可以刷新令牌,但是我不知道如何重新发送以前失败的请求并刷新该特定组件。

previousUrl: any;
requestdata: any;

method: any;
url: any;
body: any;

private _refreshSubject: Subject<any> = new Subject<any>();

private _ifTokenExpired() {
    this._refreshSubject.subscribe({
        complete: () => {
            this._refreshSubject = new Subject<any>();
        }
    });
    if (this._refreshSubject.observers.length === 1) {
        let obj = { refresh_token: localStorage.getItem('refresh_token')};
        this.api.refreshtoken(obj).subscribe(
            (resp) => {
                localStorage.setItem('TOKEN', resp.data.access_token);
                localStorage.setItem('refresh_token', resp.data.refresh_token);
            },
            err => {
                if (err) {
                    this.router.navigate(['/login']);
                }
            });
    }
    return this._refreshSubject;
}
private _checkTokenExpiryErr(error: HttpErrorResponse): boolean {
        return (
            error.status === 403 || error.status === 401
        );
    }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  this.router.events.filter(event => event instanceof NavigationStart).subscribe(e => {
    this.previousUrl = e;
  });
  if (request.url.endsWith('/refresh')) {
    return next.handle(request);
  } else {
     return next.handle(request).pipe(retry(0),
       catchError((error, caught) => {
         this.requestdata = request;
         this.method = this.requestdata.method;
         this.url = this.requestdata.url;
         this.body = this.requestdata.body;

         if (error instanceof HttpErrorResponse) {
          if (this._checkTokenExpiryErr(error)) {
           return this._ifTokenExpired().pipe(
             switchMap(() => {
               return next.handle(this.updateHeader(request));
             })
           );
         } else {
           return throwError(error);
         }
       }
       return caught;
     })
   );
 }
}
updateHeader(req) {
   const authToken = localStorage.getItem('TOKEN');
   req = req.clone({
     headers: req.headers.set('Authorization', `Bearer ${authToken}`)
   });
   return req;
}

0 个答案:

没有答案