javascript - 如何将可观察数据通过管道传输到可观察数组?
问题描述
如何将可观察数据通过管道传输到可观察对象数组中,并将其与内部的另一个可观察对象映射?
考虑以下 observable$:
getItems$()
返回以下数据:
[
{item: 1, value: 'one'},
{item: 2, value: 'two'},
{item: 3, value: 'three'},
...
]
所以我的问题是,如何将上面的 observable 映射到一个新的 observable 中,以便在其中映射和展开另一组 observable。
预期结果:
[
{item: 1, value: 'one', prop: 'someValueMappedFromAnotherObservableMethod1'},
{item: 2, value: 'two', prop: 'someValueMappedFromAnotherObservableMethod2'},
{item: 3, value: 'three', prop: 'someValueMappedFromAnotherObservableMethod3'},
...
// here someValueMappedFromAnotherObservableMethod1 is the value that should be obtained as a result of flatMapping observable inside the ```items.map()``` fn.
]
这是我尝试过的。它不工作。它不是在内部映射和展开可观察对象items.map()
this.getItems$()
.pipe(
flatMap((items) =>
items.map((item) => ({...item, prop: this.anotherMethodReturningObservableBasedOnItemValue$(item.value))}),
),
)
.subscribe(console.log);
但是上面的一个没有按预期工作。让我知道如何做到这一点/
我也尝试过这种方式:
this.getItems$()
.pipe(
flatMap((items) =>
merge(items.map((item) => this.anotherMethodReturningObservableBasedOnItemValue$(item.value))).pipe(
combineAll(),
),
),
)
.subscribe(console.log);
解决方案
您可以通过以下方式实现您想要的:
this.getItems$()
.pipe(
mergeMap(items =>
from(items)
.pipe(
mergeMap(item =>
this.anotherMethodReturningObservableBasedOnItemValue$(item.value)
.pipe(
take(1), // toArray operator below requires all sources to complete
map(prop => ({ ...item, prop })) // Combine new prop with existing props
)
),
// Combine all items into single array
toArray()
)
)
)
.subscribe(console.log);
推荐阅读
- gradle - sourceSets 与 getAllSomeDirs 方法
- javascript - AWS Amplify 配置:重用身份验证资源
- wix - 如何仅使用 wix 工具集复制文件,无产品无更新,无卸载
- python - 在 Django 社交媒体项目中获取用户的关注者列表
- node.js - 如何查看通过 SAM 本地调用 Lambda 的完整日志?
- node.js - React 无法渲染画布事件
- ajax - 当我在 Ajax 中发布第二个查询时,我得到了 403 禁止。(Ajax + codeigniter 3 + 数据表)
- angular - 未找到 ModalBackdropComponent 的组件工厂。你把它添加到@NgModule.entryComponents 了吗?
- c++ - c++ long to char array (8 byte) to long
- r - 根据几种模式重新排序 R 向量