How to make a sequence of http requests in Angular 6 using RxJS
I have faced same problem, this is my solution use pipe
and concatMap
for array for get sequence data for time period between start and end time.
This is general solution when we have array request.
I share for whom concern.
let currentReplayData = [];
let timerange = [[t1, t2], [t3, t4]]; // array of start and end time
from(timerange).pipe(
concatMap(time => <Observable<any>>this.dataService.getData(time[0],time[1]))
).subscribe(val => {
//console.log(val)
this.currentReplayData = this.currentReplayData.concat(val);
});
MergeMap
is exact what you are looking for
firstPOSTCallToAPI('url', data).pipe(
mergeMap(result1 => secondPOSTCallToAPI('url', result1)),
mergeMap(result2 => thirdPOSTCallToAPI('url', result2)),
mergeMap(result3 => fourthPOSTCallToAPI('url', result3)),
// ...
).subscribe(
success => {
// here you will get response of LAST request (fourthPOSTCallToAPI)
},
errorData => { /* display error msg */ }
);
// I assume that
// secondPOSTCallToAPI, thirdPOSTCallToAPI and fourthPOSTCallToAPI
// returns obserwable eg. return this.http.get<Book>(apiUrl);
For calls that depend on previous result you should use concatMap
firstPOSTCallToAPI('url', data).pipe(
concatMap(result1 => secondPOSTCallToAPI('url', result1))
concatMap( result2 => thirdPOSTCallToAPI('url', result2))
concatMap(result3 => fourthPOSTCallToAPI('url', result3))
....
).subscribe(
success => { /* display success msg */ },
errorData => { /* display error msg */ }
);
if your async method does not depend on return value of the precedent async call you can use
concat(method(),method2(),method3()).subscribe(console.log)