[英]Angularfire2 Observable Recursion
I am attempting to create a "breadcrumbs" list by looping through documents and grabbing their parents. 我试图通过遍历文档并抓住他们的父母来创建“面包屑”列表。 My data structure looks like so:
我的数据结构如下所示:
storage-unit: 存储单元:
I am attempting to make an array of a single unit's tree of parents. 我正在尝试对单个单元的父级树进行排列。 I'm trying to use recursion, as I would assume that's the easiest way of doing it.
我正在尝试使用递归,因为我认为这是最简单的方法。 I know without observables, it would be something like the following:
我知道如果没有可观察到的东西,它将类似于以下内容:
// Unit is an observable returned by valueChanges()
recurseParents(unit){
if (unit === null) {
return;
}
// Titles array defined onInit in Angular
this.titles = [...unit, this.titles];
recurseParents(this.unitService.getUnitById(unit.parent));
}
With Angularfire2's observables, I'm not sure how to accomplish this. 使用Angularfire2的可观察对象,我不确定如何实现此目的。 I tried doing the same-ish steps within a subscribe, and it produced odd behavior at times, even doing .take(1) before calling subscribe.
我尝试在订阅中执行相同的步骤,有时会产生奇怪的行为,甚至在调用订阅之前执行.take(1)。
The end goal is to look like this: 最终目标是这样的:
[{root parent}, {sub parent 1}, {sub parent 2}, {original document}]
You can use the .expand()
operator, and it is just a one liner: 您可以使用
.expand()
运算符,它只是一个衬里:
expand(unit => unit === null ? empty() : this.unitService.getUnitById(unit.parent))
Note: empty()
returns an observable that is empty and terminate the stream immediately. 注意:
empty()
返回一个可观察值,它为空,并立即终止流。
So you can just do something along the lines: 因此,您可以按照以下方式做一些事情:
let rootDoc$ = of(this.titles) //assign to the observables of your DocumentRef
rootDoc$
.pipe(
expand(unit => unit === null ? empty() : this.unitService.getUnitById(unit.parent))
)
.subscribe(unitValues => {
this.titles = [...unitValues, this.titles];
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.