首页 > 解决方案 > 如何递归地加入两个嵌套的可观察对象

问题描述

我有一个可观察的数组, 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] }

我怎样才能使这个结果变平?

标签: javascriptnode.jstypescriptrxjs

解决方案


我不确定你为什么需要以非常必要的方式使用如此复杂的 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如果您希望父母和孩子随机到达,您也可以在现实世界中使用。一旦每个流至少发射一次,这将开始发射。


推荐阅读