如何完成嵌套的Observables? [英] How to finalize nested Observables?
本文介绍了如何完成嵌套的Observables?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请看下面的尝试,以更好地理解:
Please, take a look at the following try for better understanding:
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
.
My goal is to set the loading
property to false
just at the end of the request or requests if that is the case.
我希望已经很好地解释了我的问题.预先感谢.
I hope to have explained my problem well. Thanks in advance.
推荐答案
您应使用 switchMap 运算符,将两个可观察值合并为一个:
You should use the switchMap operator to combine the two observables into one:
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
});
这篇关于如何完成嵌套的Observables?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文