【问题标题】:finally() is not called when returning empty() in catch()在 catch() 中返回 empty() 时不调用 finally()
【发布时间】:2017-02-02 09:58:02
【问题描述】:

我编写了一个通用请求方法,它应该在请求运行时显示加载指示器。如果发生错误(比如 404),我会在.catchreturn Observable.empty() 中显示消息,这样下面的代码就不会崩溃(因为没有返回数据)。

最大的问题是 .finally 也不会被调用。那是一个错误吗?有解决方法吗?这是我的代码:

res = Observable
  .of(true)
  .do(() => this.store.dispatch(new ShowLoadingIndicatorAction()))
  .switchMap(() => this.http.get(url, { headers: this.headers }))
  .publishReplay(1)
  .refCount()
  .catch(error => {
    this.messages.handleRequestError(error);
    return Observable.empty();
  })
  .finally(() => this.store.dispatch(new HideLoadingIndicatorAction()));

// then later:
res.subscribe(doStuffWithData);

【问题讨论】:

    标签: rxjs5


    【解决方案1】:

    您使用的是什么 RxJS 版本?它在这个例子中运行良好:

    const res$ = Rx.Observable
      .of(true)
      .switchMap(() => Rx.Observable.throw("Rest Error"))
      .publishReplay(1)
      .refCount()
      .catch(error => Rx.Observable.empty())
      .finally(() => console.log("Calling Finally!"));
    
    res$.subscribe(console.info);
    <script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script>

    【讨论】:

    • 天啊,你似乎是对的!我正在使用 5.0.3。似乎在 Ionic 中显示一条消息会阻止加载指示器......我应该使用 console.log 来测试它。谢谢,对不起:)
    • 好的 - 也许你也可以用“Ionic”标记这个问题,然后自己提供一个答案,以防其他人偶然发现这个问题:)
    • 好吧,这个问题似乎没那么有用:事实证明我们的应用显示了几个加载指示器,其中一个没有关闭,因为该流中实际上缺少 .finally() 调用。所以一切都按预期工作,问题出在键盘前面....
    猜你喜欢
    • 2011-11-04
    • 2014-04-27
    • 2012-05-20
    • 2018-11-05
    • 2016-03-28
    • 2015-10-24
    • 1970-01-01
    • 2012-02-10
    • 2021-05-30
    相关资源
    最近更新 更多