Apply Retry Operator for specific API’s

Mohammedfahimullah
2 min readJun 3, 2022

Recently came across a scenario where I was told for some specific API’s retry RXJS operator should not be applied. So In this article, we will see how to apply the Retry Operator for the same.

Service.ts

http-service.ts

Above is our service file where there are 2 GET API’s. Out of which, the getAPIWithError() will always give you a 404 error. In both the API’s you can see that there is an optional parameter called headers. We will be passing the additional optional header details in the API’s. We will be using these additional details to execute our functionality.

app.component.ts

app.component.ts

I have called both the API’s in ngOnInit. Let’s say whenever getAPIWithError API returns an error I want to retry the API call for some x times. In that case, I have added the additional headers function retryCall() and it has to be passed to all API’s where you want to retry the API call if it errors out.

retry call function

This is a common function that I have added. In my code this function I have added in the app.component.ts file. In your case this function we can add to our common file so that we can use it across all our components. In this function, we are just creating a key: value pair and returning the headers in an object.

retry-interceptor.interceptor.ts

In the retry Interceptor we can check the additional headers which was passed in our API call based on that we can apply the retry operator.

let isretry = request.headers.get('retryCall');

We can get the additional header which was passed in the API from the request parameter.

Retry Calls

As you can see in the above image the errored API called has called 5 times. Since we have mentioned our retry count as 5 in the interceptor.

A demo link has been provided here

--

--