how to send independent http request in sequence angular

心已入冬 提交于 2019-12-25 00:38:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!