Angular HttpClient RXJS 在不工作时重试

Angular HttpClient RXJS retrywhen not working

在 angular 中,我是 httpClient 的新手,正在尝试实现一个解决方案,以便在互联网断开时重试 http 调用,即错误状态 = 0。当 3 次尝试失败时,我希望它抛出原始 http响应错误。

以下是我正在尝试的方法,但它不起作用。有什么想法吗?

return this.httpClient.post('https://server.com/logins', data, {headers: headers})
      .pipe(retryWhen(errors => errors
        .pipe(map((err, index) => {          
          // Caught Error, throw immediately
          if (!err) {
            throw err;
          } 
          if (err.status !== 0) {
            throw err;
          }
          // Disconnection error
          if (index === 2) {
            throw err;
          }
          return err;
        }))
        .pipe(delay(1000)))) 

这个解决方案应该可以工作,如果不能请你给我一个 stackblitz,我会尽力让它工作

 return this.httpClient.post('https://server.com/logins', data, { headers: headers })
      .pipe(
        retryWhen(errors => errors
          .pipe(
            concatMap((error, count) => {
              if(count === 3 && error.status === 0) {
                  return throwError(error);
              } 
              return of(count); 
            }),
            delay(1000)
          )
        )
      );

所以我所做的主要更改是通过 concatMap 的第二个参数跟踪错误计数,我想你想抛出一个错误。如果需要,您可以轻松更改条件。