简体   繁体   English

"如何按顺序发送独立的http请求"

[英]How to send independent http request in sequence angular

I want to send 10 requests that are independent, one after the other in sequence.我想依次发送10个独立的请求。 and want to get all the results in an array.并希望在一个数组中获得所有结果。 I have tried forkJoin<\/code> but it hit all the requests in parallel.我试过forkJoin<\/code>但它同时满足了所有请求。

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);
}

You need to use concat instead. 你需要使用concat

concat will subscribe to first input Observable and emit all its values, without changing or affecting them in any way. concat将订阅第一个输入Observable并发出其所有值,而不以任何方式更改或影响它们。 When that Observable completes, it will subscribe to then next Observable passed and, again, emit its values. 当Observable完成时,它将订阅然后传递下一个Observable,并再次发出其值。 This will be repeated, until the operator runs out of Observables. 这将重复,直到操作员用尽Observables。 When last input Observable completes, concat will complete as well. 当最后一个输入Observable完成时,concat也将完成。

If you then want to gather all those results into an array you will need to use the toArray operator to collapse the results. 如果您希望将所有这些结果收集到一个数组中,则需要使用toArray运算符来折叠结果。

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

Solution (concatMap keeps the order of the requests)解决方案(concatMap保持请求的顺序)

   const results = [];
   search(queryUrls) {
       from(queryUrls).pipe(
         concatMap((query) => this.http.post(query.url, query.data)),
         catchError(e => of('Error'))
       ).subscribe((response) => results.push(response.body));
    }

Explanation: Difference between mergeMap, switchMap and concatMap说明: mergeMap、switchMap、concatMap的区别

if you want to send the results in another observable when all the requests are done, you can do so this way如果你想在所有请求完成后将结果发送到另一个 observable 中,你可以这样做

output$ = new Subject();
   search(queryUrls) {
       const results = [];
       from(queryUrls).pipe(
         concatMap((query) => this.http.post(query.url, query.data)),
         catchError(e => of('Error'))
       ).subscribe(
         (response) => results.push(response.body),
         () => {},
         () => { output$.next(results); } // this is executed on complete
       );
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM