alim1990
alim1990

Reputation: 4972

Angular and Http Calls How to make an http call to keep trying until a success response is received?

We are migrating data from a system into another. These data are composed of two excel files.

The first one contains the basic/general information about a family, and the other is information about each member of each family.

The script is composed of two nested loops. The first loop will take a row from the excel, add it into the database then the second loop, will search for related members (using a unique ID for each family) and add them as well.

I wrapped the HTTP calls, inside promise. When a promise is resolved, we will move to the next step, if not, an array will be added to a log file saying that this row had an issue while uploading and we will check it later.

Sometimes, when handling HTTP calls from an observable, some of the calls will be ahead of others that should not be. Let us say, that family X is being added, and there is 5 HTTP calls are running, if one of them, had a late response and the initial loop is started with uploading info of family Y, the code will break, because of the structure of the new system we are migrating to.

Long story short, while uploading data, we receive an error 500: Internal Server Error without knowing the reason. But we expected that this is going to happen, so we did the following at our api.services.ts service:

postData(data) {
    const url = 'apiUrlForDataUpload';
    return this.http.post(url, data, this.httpOptions).pipe(retry(3), timeout(15000));
}

I am specifying that in case the server returned an error, to repeat the call at least 3 times, and in case there was a network interruption, to wait for 15 seconds before skipping into next part.

The problem is that whenever the server returns an error, the loop will be broke and the call would not retry the process for 1 time at least not 3.

How to make an HTTP call to keep trying until a success response is received?

Upvotes: 0

Views: 950

Answers (2)

Aakash Garg
Aakash Garg

Reputation: 10969

postData(data) {
  const url = `apiUrlForDataUpload`
  return this.http.post(url, data, this.httpOptions).pipe(retryWhen(err => err.pipe(delay(timer(2000)))));
)

Upvotes: 2

satanTime
satanTime

Reputation: 13539

You can use catchError and retry() (without the number).

        this.httpClient.get('http://doesnot.exist').pipe(
            tap(
                () => console.log('emit'),
                () => console.log('error'),
                () => console.log('complete'),
            ),
            // a short delay in a retry.
            catchError(error => timer(1500).pipe(switchMapTo(throwError(error)))),
            retry(),
        ).subscribe();

Upvotes: 1

Related Questions