首页 > 解决方案 > 如何使用 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.list3this.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.

标签: javascriptangulartypescriptrxjs5

解决方案


除了其他答案之外,您还可以将输入 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);
  }
);

推荐阅读