javascript - 如何递归地加入两个嵌套的可观察对象
问题描述
我有一个可观察的数组, parents$ 和 children$ 定义如下。然后我有一个班级AttachChildren。该类有一个方法 getChild$(parentId) 用于获取给定父级的相关子级。最后,方法 tesCollection() 用于填充 parent$ 项目的 'children' 属性。我曾尝试使用 forkJoin 尝试合并两个流,以便获得最终数据,但到目前为止还没有成功。吹的是相关数据和类。我在 node.js 和 rxjs 版本“^7.3.0”中使用打字稿。
const parents$ = of([
{
parentName: 'a',
parentId: 0,
children: []
},
{
parentName: 'b',
parentId: 1,
children: []
},
{
parentName: 'c',
parentId: 2,
children: []
},
]);
const children$ = of([
{
parentId: 0,
childName: 'a-a',
childData: [
{
itemId: 0,
itemName: 'd'
},
{
itemId: 1,
itemName: 'e'
}
]
},
{
parentId: 2,
childName: 'a-b',
childData: [
{
itemId: 0,
itemName: 'f'
},
{
itemId: 1,
itemName: 'g'
}
]
}
]);
我需要孩子通过 parent$ 和 children$ 共有的相关 parentId 属性附加到父母;我尝试过的是:
class AttachChildren{
tesCollection() {
parents$
.pipe(
mergeMap((m: Parent) => {
return m.map(parent => {
const child$ = this.getChild$(parent.parentId);
return forkJoin(
{
parent: of(parent),
child: child$
}
)
})
})
)
.subscribe((p: any) => {
console.log('subscribe/parents:', p);
});
}
getChild$(parentId: number): Observable<Child> {
return children$
.pipe(
mergeMap(c => c.map(child => child.parentId === parentId))
)
}
}
我得到的结果如下:
subscribe/parents: Observable { _subscribe: [Function] }
subscribe/parents: Observable { _subscribe: [Function] }
subscribe/parents: Observable { _subscribe: [Function] }
我怎样才能使这个结果变平?
解决方案
我不确定你为什么需要以非常必要的方式使用如此复杂的 RxJS。我更喜欢以更实用的方式使用它。
这是一个将父母和孩子联系起来的片段。即使这不完全是您想要的答案,我希望它能让您大致了解代码可以变得多么简单(阅读和维护)和更少的必要性。
forkJoin({
parents: parents$,
children: children$,
}).pipe(
map(({children, parents}) => {
const getChildrenOfParent = id => {
return children.filter(child => child.parentId === id)
}
return parents.map(parent => ({
...parent,
children: getChildrenOfParent(parent.parentId)
}));
})
).subscribe(console.log)
输出是:
我在forkJoin
这里使用,因为这是一个 Observable 创建者,它将在所有流完成时发出 - 这对于of
在本例中组合多个非常好。combineLatest
如果您希望父母和孩子随机到达,您也可以在现实世界中使用。一旦每个流至少发射一次,这将开始发射。
推荐阅读
- java - 如何将引用指针更改为另一个对象
- php - 什么类型的项目节点可以用js代替php
- reactjs - 无论如何将javascript控制台日志推送到哨兵
- mysql - mysql对每一行求和
- c# - 每次运行应用程序时,Asp.net 核心 Log4net 日志记录消息都会覆盖在日志文件中
- mysql - 如何从Mysql中的一个存储过程连接两台不同的Mysql服务器?
- sql - 对连续整数求和和分组
- arrays - How do I transfer the array to the routing parameter?
- c# - MySQL 服务器错误 - 您的 SQL 语法有错误
- python - 为什么我的具有函数作用域的 pytest 夹具返回的对象在新测试中没有重置它的类变量?