In a perfect world, everybody would have a fast net connection all the time. But at present, your users can find themselves repeatedly banging their heads on their keyboards as they wait for the internet to come back.

But you can prepare for that and have your application identify and deal with failed HTTP requests, ensuring your users have a better experience.

Warning: The following code was written during 5 minutes of boredom when my internet was down. Beats banging the keyboard with your head. 🤕

Let’s combine the power of RxJS and HTTP interceptors and learn how we achieve this behavior.

We can use the retryWhen operator to tell the application when we want to subscribe to the HTTP request again. That’s done by giving a function where the input is the error observable, and the output is an observable that indicates when the application should resubscribe to the source.

First, we check if the user is online. If that’s the case we throw the error so that any subscribers get it as we don’t need to handle it; Otherwise, we want to resubscribe once we get a notification that we’re online again.

Let’s see a live demo:

I’m using a service that slows the response so I can simulate an offline mode quickly.

Live demo GET request

Let’s see another one with POST request:

Live demo POST request

This is only a taste of what we can do. For instance, we can take it a step further, and also block similar requests, etc.

🔥 Last but Not Least, Have you Heard of Akita?

Akita is a state management pattern that we’ve developed here in Datorama. It’s been successfully used in a big data production environment, and we’re continually adding features to it.

Akita encourages simplicity. It saves you the hassle of creating boilerplate code and offers powerful tools with a moderate learning curve, suitable for both experienced and inexperienced developers alike.

I highly recommend checking it out.

Follow me on Medium or Twitter to read more about Angular, Akita and JS!