如何按顺序发送独立的http请求 [英] how to send independent http request in sequence angular

查看:82
本文介绍了如何按顺序发送独立的http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想发送10个独立的请求,一个接一个地依次发送.并希望将所有结果都放在一个数组中.我尝试了 forkJoin ,但它同时满足了所有请求.

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.

用于并行请求

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?

推荐答案

您需要使用 <代替 concat .

You need to use concat instead.

concat将订阅第一个输入Observable并发出其所有值,而不会以任何方式更改或影响它们.当该Observable完成时,它将订阅然后传递的下一个Observable,并再次发出其值.将重复此操作,直到操作员用完Observable.当最后一个输入Observable完成时,concat也将完成.

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.

如果您随后想要将所有这些结果收集到一个数组中,则需要使用 toArray 运算符来折叠结果.

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 => /**/)

这篇关于如何按顺序发送独立的http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆