让我们说我们有一个分层的数据结构-即,每个项目可能有一个或多个子代,并且这些子代通过父ID链接。
让我们也想从当前组一直循环到父组以获取结构。
虽然大多数Angular文档似乎都是在While循环中引用使用Observables的(即while parentId!= undefined),但是我们有一个问题是while循环可能会持续几次,因为我们正在订阅的输出在可观察性实现之前我们不会得到的可观察性。
while (childGroup.parentGroupId !== undefined) {
this.groupsService.getGroup(childGroup.parentGroupId).subscribe(group => {
groupHierarchy.unshift(group);
childGroup = group;
});
}
所以我们可能需要做一个CombineLatest,以便我们可以一起处理所有可观测对象。
while (childGroup.parentGroupId !== undefined) {
observables.push(this.groupsService.getGroup(childGroup.parentGroupId))
}
combineLatest(observables).subscribe( data => { // Process Here });
当我要收集数据列表时,我在其他几个示例中使用了此方法,但我想知道是否有原因为什么我们不使用Promise而不是Observable吗?:
this.groupsService.getGroup2(childGroup.parentGroupId).then(group => { groupHierarchy.unshift(group); childGroup = group; } )
实际上,除非您能想到其他解决方案,否则我可能仍需要使用此方法。在确定下一个父节点是什么之前,我必须等待获取当前节点的父节点。
您的想法受到赞赏。