Угловой перехватчик HttpClient: обновить токен авторизации - PullRequest
0 голосов
/ 01 мая 2019

Вот мой код перехватчика

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 голосов
/ 01 мая 2019

Убедитесь, что вы сбросили ошибку или вернули наблюдаемое.Оператор 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);
          }));
0 голосов
/ 01 мая 2019

Можете ли вы попробовать это?

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);
          }
        }
      }
    );
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...