简体   繁体   中英

How to send independent http request in sequence angular

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<\/code> 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);
}

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

Solution (concatMap keeps the order of the requests)

   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

if you want to send the results in another observable when all the requests are done, you can do so this way

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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