Angular 5 HttpInterceptor重试请求

时间:2018-01-19 20:21:11

标签: angular

Angluar 5 HttpInterceptor如何在错误时重试请求?

Angular文档没有显示HttpInterceptor重试的示例: https://angular.io/guide/http https://angular.io/api/common/http/HttpInterceptor

请注意,HttpClient对象上有重试。在这种情况下,这没有用。

Psuedo逻辑我试图实现: 发送请求 IF错误响应然后更改请求并重试请求。

此HttpInterceptor成功运行请求并捕获错误但不重试请求。

export class AuthInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        return next
            .handle(req)
            .do(event => {
            }, (err: any) => {
                let reqRepeat = req.clone(); // For now, keep it simple. Don't change original request.
                return next.handle(req); // Retry request. THIS DOESN'T SEEM TO DO ANYTHING!
            })
    }
};

2 个答案:

答案 0 :(得分:3)

rxjs'do'运算符不会修改观察者。返回'next.handle(...)'应该不起作用。

尝试使用'catch'操作符。

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).catch(() => {
      const newReq = req.clone();
      return next.handle(newReq);
    });
  }

不要忘记导入catch操作符:

import 'rxjs/add/operator/catch';

答案 1 :(得分:1)

我总是使用此代码进行身份验证,因此我将使用主题来实现此逻辑

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpErrorResponse } from '@angular/common/http';
import { AuthService } from '../services/auth.service';
import { Observable, throwError, BehaviorSubject } from 'rxjs';
import { catchError, filter, take, switchMap } from 'rxjs/operators';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

  private isRefreshing = false;
  private refreshTokenSubject: BehaviorSubject<any> = new BehaviorSubject<any>(null);

  constructor(public authService: AuthService) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    if (this.authService.getJwtToken()) {
      request = this.addToken(request, this.authService.getJwtToken());
    }

    return next.handle(request).pipe(catchError(error => {
      if (error instanceof HttpErrorResponse && error.status === 401) {
        return this.handle401Error(request, next);
      } else {
        return throwError(error);
      }
    }));
  }

  private addToken(request: HttpRequest<any>, token: string) {
    return request.clone({
      setHeaders: {
        'Authorization': `Bearer ${token}`
      }
    });
  }

  private handle401Error(request: HttpRequest<any>, next: HttpHandler) {
    if (!this.isRefreshing) {
      this.isRefreshing = true;
      this.refreshTokenSubject.next(null);

      return this.authService.refreshToken().pipe(
        switchMap((token: any) => {
          console.log('Token refreshed');
          this.isRefreshing = false;
          this.authService.saveAccessToken(token['access']);
          this.refreshTokenSubject.next(token['access']);
          return next.handle(this.addToken(request, token['access']));
        }),catchError(error => {
          console.log('hi88888888888888');
          if (error instanceof HttpErrorResponse && error.status === 401) {
            this.authService.logout();
            return
          } else {
            return throwError(error);
          }
        }));

    } else {
      return this.refreshTokenSubject.pipe(
        filter(token => token != null),
        take(1),
        switchMap(jwt => {
          console.log(jwt);
          return next.handle(this.addToken(request, jwt));
        }));
    }
  }
}