RetryWhen in interceptor Angular 2
2021
import { Injectable } from '@angular/core';import {HttpRequest,HttpHandler,HttpEvent,HttpInterceptor,HttpErrorResponse,} from '@angular/common/http';import { Observable, of, throwError } 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: [408, 429, 500, 502, 503, 504],};constructor(private loading: LoadingService,) { }intercept(request: HttpRequest<unknown>,next: HttpHandler): Observable<HttpEvent<unknown>> {if (this.accessToken) {request = this.addToken(request, this.accessToken);}return next.handle(request).pipe(retryWhen((error) =>// Retry requesterror.pipe(concatMap((err, count) => this.retryContent(err, count)),delay(this.retry.delay))),catchError((error) => {// HttpErrorResponseif (error instanceof HttpErrorResponse) {if (error.status === 401) {// TODOreturn throwError(error);}}}),finalize(() => {this.loading.off();}));}private get accessToken(): string {return localStorage.getItem('accessToken');}private addToken(request: HttpRequest<any>,token: string): HttpRequest<unknown> {return request.clone({headers: request.headers.set('accessToken', `bearer ${token}`),});}private retryContent(error, count): 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