How to exclude certain urls from RxJS retry

Viewed 65

I have an angular 6 app that is configured to retry http requests 3 times on failure. I would like to exclude certain urls from that policy: /login (for example).

Is there a way to do that?

I could not find any answers in the RxJs documentation.

Thank you for any help

Here's my code:

@Injectable()
export class RetryInterceptor implements HttpInterceptor {
    constructor( public spinnerService: NgxSpinnerService ) { }   
   
    timer: any;
    intercept(req: HttpRequest<any>, next: HttpHandler):
        Observable<HttpEvent<any>> {
         
            if(this.timer){
                clearTimeout(this.timer);
              }
              this.timer = setTimeout(() =>  this.spinnerService.show(), 500);           

            let handleObs: Observable<HttpEvent<any>> = next.handle(req)
            .pipe(                                        
                 retry(3),
                 finalize(() =>{
                    this.spinnerService.hide();
                    if(this.timer){
                        clearTimeout(this.timer);
                      }
                 }
                 )             
            );          

        return  handleObs;
    };
}
1 Answers

First you will have to create a function where we will be creating a HTTP headers object and we will add a custom header field(Key: value pair). This header can be passed an additional parameter in our API calls. We can use the header in the interceptor and we can write logic of our own.

 export function retryCall() {
      let headers = new HttpHeaders();
      headers = headers.set('retryCall', 'true');
      return { headers: headers };
    }

Add this above function in your common file.

intercept(
    request: HttpRequest<unknown>,
    next: HttpHandler
  ): Observable<HttpEvent<unknown>> {
    let isretry = request.headers.get('retryCall');
    let count = 0;
    return next.handle(request).pipe(
      tap((s) => console.log(count++)),
      retry(isretry ? this.retryCount : 0)
    );

In your interceptor file access the header and use the retry operator using ternatory operator.

this.httpService.getAPIWithError(2, retryCall()).subscribe((data) => {
      console.log('data: ', data);
    });

Pass the retryCall Function like above in your code. This is an optional Parameter.

 getAPIWithError(id: number, headers?: any) {
    return this.httpClient.get(
      `https://jsonplaceholder.typicode.com/todos/2/${id}`,
      headers
    );
  }

If you need code you can check the below link.

https://stackblitz.com/edit/angular-retry-rxjs-interceptor?file=src%2Fapp%2Fapp.module.ts,src%2Fapp%2Fhttp-service.ts,src%2Fapp%2Fretry-interceptor.interceptor.ts,src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.html

If you want the explanation of my code you can check my medium article. https://mohammedfahimullah.medium.com/apply-retry-operator-for-specific-apis-478f93742492

Related