问题
Here, I've used forkJoin
from rxjs to subscribe to an array of observables parallelly. But I want to subscribe to them one by one, What will be the best solution?
Below is my code :
var observables = [];
Observable.forkJoin(observables)
.subscribe(() => {
this.msgs = [];
this.msgs.push({
severity: 'success',
summary: 'Saved Successfully'
});
this.onSaveComplete();
}, (error: any) => this.errorMessage = <any>error);
}, (error: any) => this.errorMessage = <any>error);
回答1:
Alternate of forkJoin means you need to subscribe to the array of observables sequencially. merge
and concat
are the ways to go in this case. In your case, modify your code and use a spread operator at the very beginning of your array of observables when using merge
and concat
.
var observables = [];
Observable.concat(...observables)
.subscribe(() => {
this.msgs = [];
this.msgs.push({
severity: 'success',
summary: 'Saved Successfully'
});
this.onSaveComplete();
}, (error: any) => this.errorMessage = <any>error);
}, (error: any) => this.errorMessage = <any>error);
回答2:
Use the switchMap operator to make a series of dependant requests. Error will propagate and you can catch or otherwise handle them at the end of the chain.
return this.http.get('something/1')
.switchMap(res1 => {
// use res1 if you need it
return this.http.get('something/2')
})
.switchMap(res2 => {
// use res2 if you need it
return this.http.get('something/3')
})
.subscribe(res3 => {
// use the final response
console.log(res3)
})
来源:https://stackoverflow.com/questions/46388455/sequential-subscription-to-an-array-of-observables