【问题标题】:Angularfire2 Observable RecursionAngularfire2 可观察递归
【发布时间】:2018-10-29 20:23:25
【问题描述】:

我正在尝试通过循环浏览文档并获取他们的父母来创建一个“面包屑”列表。我的数据结构如下所示:

存储单元:

  • 父级:DocumentRef 指向另一个存储单元。

我正在尝试制作单个单元的父母树的数组。我正在尝试使用递归,因为我认为这是最简单的方法。我知道如果没有 observables,它将类似于以下内容:

// 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));
}

使用 Angularfire2 的 observables,我不确定如何实现这一点。我尝试在订阅中执行相同的步骤,但有时会产生奇怪的行为,甚至在调用订阅之前执行 .take(1)。

最终目标是如下所示:

[{root parent}, {sub parent 1}, {sub parent 2}, {original document}]

【问题讨论】:

  • getUnitById 返回什么?是Observable<Object> 吗?
  • @ibenjelloun 是的。它是另一个可观察到的 firebase。

标签: angular firebase recursion rxjs angularfire2


【解决方案1】:

您可以使用.expand() 运算符,它只是一个衬里:

expand(unit => unit === null ? empty() : this.unitService.getUnitById(unit.parent))

注意:empty() 返回一个空的 observable 并立即终止流。

所以你可以做一些事情:

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];
    })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多