首页 > 解决方案 > 将 forkJoin 与包含嵌套数组的数组一起使用的正确方法是什么?

问题描述

给定以下对象数组,我需要从对端点的调用中收集一系列可观察对象

const data = [
    {
        body: [{ id: 1 }, { id: 2 }],
    },
    {
        body: [{ id: 3 }],
    },
];

const requests = data.map((entry) => entry.body.map((item) => this.someService.query(item.id).pipe(take(1))));

此操作的结果与此类似

[ [ 1, 2 ], [ 3 ] ]

或者

[[Observable, Observable], [Observable]]

在其他情况下,我已经传递给forkJoin平面数组,observables我得到了我需要的结果。但在这种情况下,使用嵌套数组的数组。forkJoin使用包含嵌套数组的数组的正确方法是什么?

标签: arraysangularrxjs

解决方案


您可能想尝试这些方面的东西。有关详细信息,请参阅内联注释。

const data = [
  {
    body: [{ id: 1 }, { id: 2 }]
  },
  {
    body: [{ id: 3 }]
  }
];

forkJoin(
  // for each item of data create an Observable, which is the result of
  // executing the inner forkJoin
  data.map(entry =>
    // the inner forkJoin executes an array of Observables obtained by 
    // invoking someService.query on each item of the body
    forkJoin(entry.body.map(item => someService.query(item.id).pipe(take(1))))
  )
).subscribe(console.log);

这里有一个stackblitz来测试它


推荐阅读