Angular HttpClient拦截器:刷新身份验证令牌

时间:2019-05-01 03:07:36

标签: angular authentication httpclient refresh-token

这是我的拦截器代码

export class AuthInterceptorService implements HttpInterceptor {
      constructor(private auth: AuthService) { }

      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const userInfo = this.auth.getAuthToken();
        const authReq = req.clone({ setHeaders: { Authorization: 'Bearer ' + userInfo.access_token, 'Content-Type': 'application/json' } });
        return next.handle(authReq)
          .pipe(catchError( err => {
            if (err instanceof HttpErrorResponse) {
              if (err.status === 401) { debugger;
                console.log('this should print your error!', err.error);
              }
            }
          }));
      }
    }

我遇到以下错误

TS2345: Argument of type '(err: any) => void' is not assignable to parameter of type '(err: any, caught: Observable<HttpEvent<any>>) => ObservableInput<{}>'.   Type 'void' is not assignable to type 'ObservableInput<{}>'.

我想知道是否有针对此问题的修复程序?我想在http拦截器中实现刷新令牌功能。

2 个答案:

答案 0 :(得分:0)

你可以试试吗?

export class AuthInterceptorService implements HttpInterceptor {
  constructor(private auth: AuthService) {}

  intercept(req: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> {
    const userInfo = this.auth.getAuthToken();
    const authReq = req.clone({
      setHeaders: {
        Authorization: "Bearer " + userInfo.access_token,
        "Content-Type": "application/json"
      }
    });

    //   return next.handle(authReq)
    //     .pipe(catchError( err => {
    //       if (err instanceof HttpErrorResponse) {
    //         if (err.status === 401) { debugger;
    //           console.log('this should print your error!', err.error);
    //         }
    //       }
    //     }));

    return next.handle(authReq).do(
      (event: HttpEvent<any>) => {

        if (event instanceof HttpResponse) {
          // do stuff with response if you want
        }

      },
      (err: any) => {
        if (err instanceof HttpErrorResponse) {
          if (err.status === 401) {
            console.log("this should print your error!", err.error);
          }
        }
      }
    );
  }
}

答案 1 :(得分:0)

确保重新抛出错误或返回可观察的结果。 CatchError运算符需要一个可观察的返回。 示例:

return next.handle(authReq)
          .pipe(catchError( err => {
            if (err instanceof HttpErrorResponse) {
              if (err.status === 401) { debugger;
                console.log('this should print your error!', err.error);
              }
            }
            return throwError(err);
          }));