Last active
April 3, 2023 08:54
-
-
Save ninadvadujkar/bb1f2804f9a73b02234bb3813304805f to your computer and use it in GitHub Desktop.
A basic Angular HTTP Interceptor to retry requests when there's an error
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http'; | |
import { Observable, timer, throwError, of } from 'rxjs'; | |
import { retryWhen, tap, mergeMap } from 'rxjs/operators'; | |
@Injectable() | |
export class HttpRequestInterceptor implements HttpInterceptor { | |
retryDelay = 2000; | |
retryMaxAttempts = 2; | |
constructor() { } | |
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { | |
return next.handle(request) | |
.pipe( | |
this.retryAfterDelay(), | |
); | |
} | |
retryAfterDelay(): any { | |
return retryWhen(errors => { | |
return errors.pipe( | |
mergeMap((err, count) => { | |
// throw error when we've retried ${retryMaxAttempts} number of times and still get an error | |
if (count === this.retryMaxAttempts) { | |
return throwError(err); | |
} | |
return of(err).pipe( | |
tap(error => console.log(`Retrying ${error.url}. Retry count ${count + 1}`)), | |
mergeMap(() => timer(this.retryDelay)) | |
); | |
}) | |
); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment