【问题标题】:Angular HttpClient RXJS retrywhen not workingAngular HttpClient RXJS 在不工作时重试
【发布时间】:2019-10-13 09:48:03
【问题描述】:

在角度方面,我是 httpClient 的新手,并尝试实施一种解决方案,以在 Internet 断开连接时重试 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)))) 

【问题讨论】:

    标签: angular rxjs httpclient


    【解决方案1】:

    如果不行,这个解决方案应该可以工作,你能不能给我一个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 的第二个参数跟踪错误计数,我认为你想抛出一个错误。如果需要,您可以轻松更改条件。

    【讨论】:

    • 感谢 concatMap 代码中的一些错误,但足以让我弄清楚。需要的更正: if (count === 3 && error.status === 0) {return throwError(error);} return of(count);
    • 如果可以进行上述修改我将接受作为答案
    • 不错!很高兴为您提供帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多