Angular › HTTP Client & Interceptors

How would you use an interceptor to automatically retry a failed HTTP request a few times before giving up?

Advanced

Answer

You combine an interceptor with RxJS's retry operator, which automatically resubscribes to a failed request a specified number of times, useful for handling brief, temporary network issues without requiring extra code in every single place that makes an HTTP call.
import { retry } from 'rxjs/operators';

export const retryInterceptor: HttpInterceptorFn = (req, next) => {
  return next(req).pipe(retry(2)); // retries up to 2 times on failure
};
Real-world example A mobile heavy app automatically retries any failed API request up to two times before showing an error, smoothing over brief network drops that are common on mobile connections, without needing extra retry logic in every service.

Common follow-ups: How would you add a delay between retry attempts instead of retrying immediately?;Should every type of request be retried, even ones that change data, like a payment submission?