请求失败时,角度拦截器重试

时间:2020-10-09 07:37:23

标签: angular

我创建了一个HTTP拦截器,如下所示。如果HTTP请求失败或状态为500,如何重试HTTP请求

我试图从RXJS添加重试运算符,但是它总是多次调用请求两次,要么失败,要么成功。

问题:仅在HTTP请求失败时如何重试?

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

    const userDetails: any = this._authTokenService.getUserDetailsFromCookie();
    const token = userDetails.userToken;

    if (token) {
      request = request.clone({
        setHeaders: {
          Authorization: "Bearer " + token,
        },
      });
    }

    return next.handle(request).pipe(
      timeout(environment.ajaxTimeout),
      map((event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) {
          const status: number = event.status;
          let responseObject = event.body;
          responseObject.status = status;

          // if found status 202 means has a refreshtoken in response then again setting it in cookie
          if (status == 202) {
            console.log(responseObject);
            alert('status 202');
            this._cookieService.set(
              "userToken",
              responseObject.body.response.data.token
            );
          }
        }

        return event;
      }),
      retry(1),
      catchError((error: HttpErrorResponse) => {
        const status: number = error.status;

        if (status == 401 || error instanceof TimeoutError) {
          this._authTokenService.deleteUserTokenFromCookie();
          this._router.navigate(["/login"]);
        }
        else if (status == 404) {
          this._router.navigate(['/page-not-found']);
        }
        else if (status == 500) {
          this._router.navigate(['/internal-server-error']);
        }

        return throwError(error);
      })
    );
  }

0 个答案:

没有答案