12 March 2021

Angular retryWhen with condition statuscode (RetryWhen in interceptor Angular 2)

RetryWhen in interceptor Angular 2

2021
import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpErrorResponse,
from '@angular/common/http';
import { ObservableofthrowError } from 'rxjs';
import {
  concatMap,
  delay,
  retryWhen,
  finalize,
  catchError,
from 'rxjs/operators';
import { LoadingService } from '../shared/services/loading.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  private retry = {
    count: 1,
    delay: 1000,
    status: [408429500502503504],
  };

  constructor(
    private loadingLoadingService,
  ) { }

  intercept(
    requestHttpRequest<unknown>,
    nextHttpHandler
  ): Observable<HttpEvent<unknown>> {
    if (this.accessToken) {
      request = this.addToken(requestthis.accessToken);
    }
    return next.handle(request).pipe(
      retryWhen((error=>
        // Retry request
        error.pipe(
          concatMap((errcount=> this.retryContent(errcount)),
          delay(this.retry.delay)
        )
      ),
      catchError((error=> {
        // HttpErrorResponse
        if (error instanceof HttpErrorResponse) {
          if (error.status === 401) {
            // TODO
            return throwError(error);
          }
        }
      }),
      finalize(() => {
        this.loading.off();
      })
    );
  }

  private get accessToken(): string {
    return localStorage.getItem('accessToken');
  }

  private addToken(
    requestHttpRequest<any>,
    tokenstring
  ): HttpRequest<unknown> {
    return request.clone({
      headers: request.headers.set('accessToken'`bearer ${token}`),
    });
  }

  private retryContent(errorcount): Observable<any> {
    if (
      count < this.retry.count &&
      this.retry.status.find((f=> f === error.status)
    ) {
      return of(error);
    }
    return throwError(error);
  }
}


0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang