Created
February 23, 2024 12:43
-
-
Save jefersonalmeida/27ee3b1fd645e1eaa826b89423873f71 to your computer and use it in GitHub Desktop.
Angular HTTP Interceptor to retry requests when there's an error
This file contains hidden or 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 { HttpEvent, HttpHandlerFn, HttpRequest } from '@angular/common/http'; | |
import { Observable, retry, timer } from 'rxjs'; | |
export function retryInterceptor( | |
request: HttpRequest<unknown>, | |
next: HttpHandlerFn, | |
): Observable<HttpEvent<unknown>> { | |
const initialDelay = 500; | |
const maxTries = 3; | |
return next(request).pipe( | |
retry({ | |
count: maxTries, | |
delay: (_, retryCount) => timer(initialDelay * retryCount ** 2), | |
}), | |
); | |
} | |
// usage | |
// export const appConfig: ApplicationConfig = { | |
// providers: [provideHttpClient(withInterceptors([retryInterceptor]))], | |
// }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment