【问题标题】:How to send data to a subscriber without using a HTTP method?如何在不使用 HTTP 方法的情况下向订阅者发送数据?
【发布时间】:2018-04-27 18:01:55
【问题描述】:

我的应用中有这段代码:

  public requestList(): Observable<Record[]> {
    return this.http.get(this.requestUrl)
      .map((response: any) => this.currentList = response.json())
      .catch(this.setError);
  }

我希望这个列表只从我的后端加载一次。所以我需要检查currentList 是否已满。如果是这样,我必须忽略http.get() 并手动将currentList 内容返回给订阅者,就像他从后端获取一样透明。我怎样才能做到这一点?

  public requestList(): Observable<Record[]> {
    if (this.currentList !== undefined) {
      // MAGIC HERE: returning content that's already in this.currentList HOW?
    }
    return this.http.get(this.requestUrl)
      .map((response: any) => this.currentList = response.json())
      .catch(this.setError);
  }

【问题讨论】:

  • 魔术:return Observable.of(this.currentList);
  • 非常感谢!你有兴趣写一个答案吗?
  • 是的,我正在写一篇更详细的文章。
  • 不需要。这解决了我的问题。这只是为了给你指出积极的一面!

标签: angular rxjs reactive-programming


【解决方案1】:

您可以使用静态 of 运算符创建一个可观察对象,该可观察对象发出提供的值(或如果您传递多个参数,则按顺序发出值)然后完成。

例子:

...
if (this.currentList !== undefined) {
  return Observable.of(this.currentList);
}
...

这里有一些关于它的文档:reactivex.iolearn-rxjs

此外,使用do/tap 运算符来修改流外部的状态可能更合适,因为您并不真正打算返回与map 不同的值。

例子:

...
return this.http.get(this.requestUrl)
  .do((response: any) => this.currentList = response.json())
...

这里有一些关于它的文档:learn-rxjs

编辑:

找到另一个类似的帖子,该帖子涉及避免重复的进行中请求,但也解决了缓存问题。因此,有关该主题的更多讨论,您可能需要查看: What is the correct way to share the result of an Angular Http network call in RxJs 5?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    • 2011-11-17
    • 2021-12-21
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    相关资源
    最近更新 更多