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

问题描述 投票:0回答:2

这是我的拦截器代码

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拦截器中实现刷新令牌功能。

angular authentication httpclient refresh-token
2个回答
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);
          }
        }
      }
    );
  }
}

0
投票

确保重新抛出错误或返回一个observable。 CatchError运算符需要一个observable才能返回。例:

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);
          }));
© www.soinside.com 2019 - 2024. All rights reserved.