Skip to content

Instantly share code, notes, and snippets.

@jefersonalmeida
Created February 23, 2024 12:43
Show Gist options
  • Save jefersonalmeida/27ee3b1fd645e1eaa826b89423873f71 to your computer and use it in GitHub Desktop.
Save jefersonalmeida/27ee3b1fd645e1eaa826b89423873f71 to your computer and use it in GitHub Desktop.
Angular HTTP Interceptor to retry requests when there's an error
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