Martheli
Martheli

Reputation: 981

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.

Upvotes: 1

Views: 3558

Answers (2)

Mrk Sef
Mrk Sef

Reputation: 8022

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

Upvotes: 2

martin
martin

Reputation: 96891

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)

Upvotes: 4

Related Questions