【发布时间】:2021-07-03 19:19:05
【问题描述】:
我有一个节点树,每次用户“扩展”一个节点时,都会调用一个 http 请求来获取它的子节点。
我正在寻找一个 RXJS 管道来递归地扩展所有树节点并发出扩展的树。
我现在的做法是对源进行变异,并在完成后输出变异的对象。 有没有办法让我简化这个地狱?可能没有变异来源。
// 'ROOT' nodes
const rootNodes = [{ id: 0, parent: true }, { id: 1000, parent: true }];
// map the root nodes to a recursive function that mutate node and returns its children observables
const getChildrenOfRoot$ = rootNodes.map(node => getChildren(node));
// call the observables, in parallels, when done, print the *** mutated *** source.
forkJoin(...getChildrenOfRoot$).subscribe(() => console.log(rootNodes));
function getChildren(node: Node): Observable<Node[]> {
return getChildrenFromServer(node.id).pipe(
// if no children returned, don't continue
filter((children: Node[]) => !!(children?.length)),
// mutate argument's .children property with the returned children array.
tap((children: Node[]) => (node.children = children)),
mergeMap((children: Node[]) => {
// mape children to observables returning either their children, or, an empty array, based on 'parent' property.
const getChildrenOfChildren$ = children.map(c => (c.parent ? getChildren(c) : of([])));
return forkJoin(...getChildrenOfChildren$);
})
);
}
【问题讨论】:
标签: rxjs