arrays - 将 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
使用包含嵌套数组的数组的正确方法是什么?
解决方案
您可能想尝试这些方面的东西。有关详细信息,请参阅内联注释。
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来测试它
推荐阅读
- apache-camel - 如何在 camel-ftp 启动之前添加日志消息?
- javascript - 仅在 javascript 中显示前 n 个复选框/元素
- javascript - 动态样式组件标签名称
- c# - 从 SQL Server Express 读取数据时出错
- windows - Gitlab windows Runner lastcontact 显示从不
- python - 从通配符列表中使用 glob 复制多个文件
- c++ - 你怎么能 emplace_back 错误的类型?
- ios - dyld:库未加载:Xcode 更新后的@rpath/libswiftCore.dylib
- asp.net - 提供两个带有一个标头/HTTP 事务的 .csv 文件
- javascript - 动态文件夹内容的图像自动滑块