Search code examples
javascriptangularrxjsangular-httpclient

Angular HttpClient request with retry and delay is sending an extra request then canceling it


Am trying to use the Angulars HttpClient service to make a request with a number of tries and a delay in between. The code works, but i noticed in the devTools network tap that in the end an extra request is sent and canceled. What am I doing wrong here is the code:

return this.http.post<LoginSuccessPayload>('/api/auth/signin', payload).pipe(
  retryWhen(errors => {
    return errors.pipe(
      mergeMap((er: any) => {
        if (er.status === 504 || er.status === 503) {
          return of(er.status).pipe(delay(1000));
        }
        return _throw({message: er.error.message || 'Notification.Core.loginError'});
      }),
      take(3),
      concat(_throw({message: 'Notification.Core.networkError'}))
    );
  })
);

Here is an Image of Firefox and Chrome network tab, there should be three request but its making four and canceling the last one enter image description here


Solution

  • Here is how I solved it. now three tries with a second delay per request and no extra canceled request

     return this.http.post<LoginSuccessPayload>('/api/auth/signin', payload).pipe(
      retryWhen(errors => errors.pipe(
        switchMap((error) => {
          if (error.status === 504 || error.status === 503) {
            return of(error.status);
          }
          return _throw({message: error.error.message || 'Notification.Core.loginError'});
        }),
        scan(acc => acc + 1, 0),
        takeWhile(acc => acc < 3),
        delay(1000),
        concat(_throw({message: 'Notification.Core.networkError'}))
      ))
    );