简体   繁体   中英

Angular Concat Multiple HTTP Requests

I would like to use concat in order to subscribe to all HTTP requests that I have in an array. The array could have 1 or multiple http requests in it. I am currently creating my observable array like this:

requestArray.push(this.updateUser());
requestArray.push(this.updateCustomer());

And then I would like the requests to be submitted one at a time so I tried using concat like this:

concat(requestArray).subscribe(results => {
   console.log(results);
})

I would assume the results would be an array of the completed requests but instead it just prints out this:

Observable{_isScaler: false, source: Observable}
Observable{_isScaler: false, _subscribe: f}

It looks like its not actually subscribing to my observables.

Plain JavaScript array is considered by concat (and basically any other operator that accepts an observable as its parameter) as so called ObservableInput where it just iterates its items and reemits every single one as a separate emissions.

So if you want concat to subscribe to items inside the array you'll have to destructurize it into parameterers:

concat(...requestArray)

If you'd like the result to be an array after all your calls have completed, you can do so like this:

concat(...requestArray).pipe(
  toArray()
).subscribe(console.log);

This is basically the same thing:

merge(...requestArray, 1).pipe(
  toArray()
).subscribe(console.log);

The difference with the second one is that you can explicitly decide how many concurrent requests you'd like. So if you want a few to run in parallel at a time without overwhelming the server, you can do so:

max 3 concurrent requests:

merge(...requestArray, 3).pipe(
  toArray()
).subscribe(console.log);

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