Skip to main content

Retry http requests with RxJS

Step 10 — Retrying Failed HTTP Requests with RxJS retry() & HttpClient

In this step of our Angular 13 tutorial, we'll see how to use the retry() operator of RxJS with HttpClient to automatically resubscribing to the returned Observable which results in resending the failed HTTP requests.

In many cases, errors are temporary and due to poor network conditions so simply trying again will make them go away automatically. For example, in mobile devices network interruptions are frequent so if the user tries again, they may get a successful response. Instead of letting users manually retry, let's see how to do that automatically in our example application.

The RxJS library provides several retry operators. Among them is the retry() operator which allows you to automatically re-subscribe to an RxJS Observable a specified number of times. Re-subscribing to the Observable returned from an HttpClient method has the effect of resending the HTTP request to the server so users don't need to repeat the operation or reload the application.

You can use the RxJS retry() operator by piping it (using the pipe() method) onto the Observable returned from the HttpClient method before the error handler.

Go to the src/app/data.service.ts file and import the retry() operator:

import { retry, catchError } from 'rxjs/operators';

Next update the sendGetRequest() method as follows:

  public sendGetRequest(){
return this.httpClient.get(this.REST_API_SERVER).pipe(retry(3), catchError(this.handleError));
}

This will retry sending the failed HTTP request three times.

In the next step, we'll see how to unsubscribe from RxJS Observables in our example home component.