如何完成嵌套的Observables?

时间:2019-08-24 13:01:11

标签: angular rxjs

请查看以下尝试,以更好地理解:

this.loading = true;
obs.pipe(
   finalize(() => this.loading = false) //If set to false here and the person has children then there will be another request and the requests are not over yet
).subscribe(person => {
    if(person && person.children){
       obs2.pipe(
          finalize(() => this.loading = false) //If only set to false here and the person has no children then the false property will never actually be set to false
       ).subscribe(children => {
          //Do stuff with response
       })
    }
})

我的目标是在请求结束时将loading属性设置为false

我希望已经很好地解释了我的问题。预先感谢。

1 个答案:

答案 0 :(得分:2)

您应该使用switchMap运算符将两个可观察值合并为一个:

this.loading = true;
loadParent().pipe(
  switchMap(parent => {
    if (person.children) {
      return loadChildrenOf(parent).pipe(
        map(children => ({ parent, children })
      )
    } else {
      return of({parent, children: [] })
    }
  }),
  finalize(() => this.loading = false)
).subscribe(({ parent, children }) => {
  // Do stuff with the parent and its children
});