问题
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
})
}
})
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.
回答1:
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
});
来源:https://stackoverflow.com/questions/57638183/how-to-finalize-nested-observables