Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 949
jay Avatar asked Jul 20 '26 16:07

jay


1 Answers

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

like image 112
Kurt Hamilton Avatar answered Jul 23 '26 05:07

Kurt Hamilton