javascript - 如何使用 fofkJoin 获得多个结果然后使用结果?
问题描述
我在 Angular 5 应用程序中有多个 http 请求。
const response1 = this.http.get('url1').subscribe(data => {
this.list1 = data;
});
const response2 = this.http.get('url2').subscribe(data => {
this.list2 = data;
});
const response3 = this.http.get('url3').subscribe(data => {
this.list3 = data;
});
const response4 = this.http.get('url4').subscribe(data => {
this.list4 = data;
});
所以我可以得到this.list1
,this.list2
和. 然后我想用这些数据来渲染 UI。我使用了顺序调用并花了一些时间。现在我想使用 forkJoin。this.list3
this.list4
我的代码喜欢。
const response1 = this.http.get('url1').subscribe(data => {
this.list1 = data;
});
const response2 = this.http.get('url2').subscribe(data => {
this.list2 = data;
});
const response3 = this.http.get('url3').subscribe(data => {
this.list3 = data;
});
const response4 = this.http.get('url4').subscribe(data => {
this.list4 = data;
});
return Observable.forkJoin([response1, response2, response3, response4]).then(this.loadUiFromAllList());
我不确定如何正确使用它?我怎样才能从 forkJoin 得到结果然后做点什么?这是为了rxjs 5.5.6.
解决方案
除了其他答案之外,您还可以将输入 observables 作为对象而不是数组发送。当订阅中的响应过多时,可以更轻松地跟踪响应。
例如。你可以像下面这样
服务
getData() {
return forkJoin(
{
url1: this.http.get('url1').pipe(catchError(e => of('url1 error'))),
url2: this.http.get('url2').pipe(catchError(e => of('url2 error'))),
url3: this.http.get('url3').pipe(catchError(e => of('url3 error'))),
url4: this.http.get('url4').pipe(catchError(e => of('url4 error'))),
}
)
然后,您可以使用订阅中的密钥来引用结果
控制器
this.dataService.getData().subscribe(
result => {
console.log(result.url1);
console.log(result.url2);
console.log(result.url3);
console.log(result.url4);
}
);
推荐阅读
- javascript - try-catch 应该如何与多个事件处理程序一起使用?
- reactjs - 'action' 没有在 reducer 中定义 - React, Redux
- qt - 如何使用 Qt QWidget 边框的 styleSheet 禁用抗锯齿
- algorithm - Kayak 搜索/数据聚合算法
- linux - 排序列表...完成!分段错误(核心转储)
- java - Hazelcast MBean 丢失
- javascript - 在所有 html 元素上进行交互的通用 javascript 选择器
- algorithm - 比质心更好的“中心点”
- javascript - “您当前未连接到受支持的页面或应用程序。” 在 Internet Explorer 11 控制台中执行 JQuery 代码时出错
- c# - 如何从 ArrayList 或 GridView c# 中删除列