【问题标题】:RxJS timeout without error when no return value is requested没有请求返回值时,RxJS 超时无错误
【发布时间】:2020-03-18 11:37:27
【问题描述】:

我正在进行不返回值的 Web api 调用,我只对它们的 HTTP 状态代码感兴趣。 但我希望这些调用在指定的时间跨度后超时。

因为我错过了阅读文档,所以我在 web-call-observable 上使用了 timeout-operator,如下所示:

this.someProvider.requestStatus(someValue)
    .pipe(timeout(this.timeoutMilliseconds))
    .subscribe(() => console.log("Success"),...)

问题是,我在订阅者函数中收到了成功的网络调用,但即使在超时时间跨度之后,调用仍然失败,因为源 observable 没有返回值 - 我认为。

当我没有得到 HTTPResponse 并且只有正文(如果有的话)时,有没有办法使用 rxjs 操作符来做到这一点?

【问题讨论】:

  • 考虑使用takeUntil 运算符
  • @KarthigeyanVellasamy 是的,我没有得到任何值,因为 api 没有发送值,尽管成功 - “回调”仍然执行,因为调用成功......但在那之后timeout-operator 仍然会抛出错误,因为没有发出任何值。
  • 所以,如果我理解正确,您不想看到错误,对吧? @Velulian
  • @Herman Lule 我不想在调用成功时发出它,即使没有省略任何值。
  • timeout 如果源 Observable 在一段时间内没有发出,则会抛出错误。但如果源代码完成,那么timeout 将停止。所以看起来你的源 Observable this.someProvider.requestStatus() 没有完成。

标签: angular typescript rxjs timeout observable


【解决方案1】:

timeout() 会在源 Observable 一段时间内不发射时抛出错误。

但如果源代码完成,那么timeout() 将停止。所以看起来你的源 Observable this.someProvider.requestStatus() 没有完成。

【讨论】:

    【解决方案2】:

    尝试像这样使用catchError 运算符:

    requestCall(...).pipe(
    catchError(err => {
    // Here you can check if the error corresponds to the one you don't want emitted
    // And if so do nothing, in this case just return an empty array like
    if(err.code === something) {
    return []
    }
    // Or return the error
    })).subscribe(.....)
    

    这将捕获错误并且什么都不做。

    【讨论】:

      【解决方案3】:
       this.someProvider.requestStatus(someValue)
          .pipe(
              timeout(this.timeoutMilliseconds)).subscribe(
              () =>console.log("Success"),
              err=> {
            if (err instanceof  TimeoutError ) {
              console.log("timed out");            
            } else {
              console.log("sth else happened",err);
            }         
          });
      

      正如您在 cmets 中提到的。您可以检查超时操作的错误实例。但是你应该注意到,如果发生超时,这将取消请求。

      【讨论】:

      • 遗憾的是,这不是我在问题中所写的选项。
      • @Velulian 你无权访问requestStatus 功能?或者修改它会在其他地方刹车?
      • 我没有访问权限。
      猜你喜欢
      • 1970-01-01
      • 2015-03-20
      • 2019-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多