angular - 如何在不使用 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);
}
解决方案
您可以使用静态of
运算符创建一个可观察对象,该可观察对象发出提供的值(或如果您传递多个参数,则按顺序发出值)然后完成。
例子:
...
if (this.currentList !== undefined) {
return Observable.of(this.currentList);
}
...
这里有一些关于它的文档:reactivex.io,learn-rxjs
此外,使用运算符来修改流外部的状态可能更合适,do/tap
因为您并不真的打算从map
.
例子:
...
return this.http.get(this.requestUrl)
.do((response: any) => this.currentList = response.json())
...
这里有一些关于它的文档:learn-rxjs
编辑:
找到了另一篇类似的帖子,该帖子涉及避免重复的飞行中请求,但也解决了缓存问题。因此,有关该主题的更多讨论,您可能需要查看: 在 RxJs 5 中共享 Angular Http 网络调用结果的正确方法是什么?
推荐阅读
- reactjs - WeatherApp - 反应
- python-3.x - Django MemcacheUnexpectedCloseError and [WinError 10061] No connection could be made because the target machine主动拒绝它
- azure-active-directory - Azure AD Connect 调用 PowerShell 进行同步
- javascript - 脚本小部件编码技术
- python - 使用 Python 将 Pub/Sub 消息加载到 BigQuery
- javascript - 输入增加减少影响购物车数组php javascript中的其他输入
- javascript - NeutralinoJS 在浏览器中打开本地 html 文件
- html - 如何使链接可跟踪(点击次数)
- android - onActivityCreated 已弃用。对于 DialogFrament,如果没有调用 onViewCreated 的替代品是什么
- python-3.x - Python将br标签替换为XML中的段落