首页 > 解决方案 > 如何在不使用 HTTP 方法的情况下向订阅者发送数据?

问题描述

我的应用程序中有此代码:

  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);
  }

标签: angularrxjsreactive-programming

解决方案


您可以使用静态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

编辑:

找到了另一篇类似的帖子,该帖子涉及避免重复的飞行中请求,但也解决了缓存问题。因此,有关该主题的更多讨论,您可能需要查看: 在 RxJs 5 中共享 Angular Http 网络调用结果的正确方法是什么?


推荐阅读