jay
jay

Reputation: 45

Dynamic amount of sequential HTTP requests in Angular

This is my first question here, sorry if it isn't detailed enough.

I am looking to make a dynamic amount of requests sequentially (could be a lot) to get data,

I would need this data to be collected from each request and returned as a final observable at the end of the last request.

I have attempted to use forkJoin to combine the requests, although, this does not make each request sequentially and then also concat, which emits and observable after each request.

Upvotes: 3

Views: 1459

Answers (1)

Kurt Hamilton
Kurt Hamilton

Reputation: 13515

You want to:

  • Make an arbitrary number of sequential HTTP requests (based on some array, I assume)
  • Return an array of results

I would use concat in conjunction with toArray here. concat will run the requests sequentially, and toArray will emit an array when all responses are available.

// some dynamic array
const source = [ 1, 2, 3, 4, 5 ];

const observables = source.map(x => this.http.get('some url'));
concat(
  ...observables
).pipe(
  toArray()
).subscribe(responses => {
  console.log(responses);
  // array of results
});

DEMO: https://stackblitz.com/edit/angular-s1fdxj

Upvotes: 9

Related Questions