3

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.

3
  • Hi, Please show some code to help us see what you've already tried Commented Mar 4, 2020 at 16:41
  • Do you know how many requests you'll need to make when you start, or is it possible that it might change while requests are being made? Commented Mar 4, 2020 at 16:42
  • @KurtHamilton Once you start, you will know how many requests you will need. Commented Mar 4, 2020 at 16:48

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

2 Comments

@Eliseo Thanks. I knew there would be a better implementation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.