问题
I want to send 10 requests that are independent, one after the other in sequence. and want to get all the results in an array. I have tried forkJoin
but it hit all the requests in parallel.
For parallel requests
search(queryUrls) {
queryUrls.forEach((query) => {
observableBatch.push(this.http.post(query.url, query.data))
.pipe(
map((res) => res),
catchError(e => of('Error'))
);
});
//
return forkJoin(observableBatch);
}
and I can subscribe this method and can get all the results in an array. but how can I send all the requests in sequence?
回答1:
You need to use concat instead.
concat will subscribe to first input Observable and emit all its values, without changing or affecting them in any way. When that Observable completes, it will subscribe to then next Observable passed and, again, emit its values. This will be repeated, until the operator runs out of Observables. When last input Observable completes, concat will complete as well.
If you then want to gather all those results into an array you will need to use the toArray
operator to collapse the results.
In your case it will look something like:
const batched = queryUrls.map(query => this.http.post(query.url, query.data))
concat(batched).pipe(toArray()).subscribe(allResults => /**/)
来源:https://stackoverflow.com/questions/55558277/how-to-send-independent-http-request-in-sequence-angular