2

I know that you can use Observable by calling forkJoin method to wait for multiple http requests to be done like below:

getBooksAndMovies() {
    Observable.forkJoin(
        this.http.get('/app/books.json').map((res:Response) => res.json()),
        this.http.get('/app/movies.json').map((res:Response) => res.json())
    ).subscribe(
      data => {
        this.books = data[0]
        this.movies = data[1]
      }
    );
  }

However, in my case, I have multiple http posts which they are dynamic like the below code, there are 2 titles, what If I have 100 or 1000 titles. How can I handle such dynamic posts request? Please suggest.

createBooksAndMovies() {
  let title = ['Hello', 'World'];
  let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
  let options = new RequestOptions({ headers: headers });
  let body1 = 'title=' + title[0];
  let body2 = 'title=' + title[1];

    Observable.forkJoin(
        this.http.post('/app/books.json', body1, options).map((res:Response) => res.json()),
        this.http.post('/app/books.json', body2, options).map((res:Response) => res.json())
    ).subscribe(
      data => {
        this.book1 = data[0]
        this.book2 = data[1]
      }
    );
  }
2
  • What's the problem? Commented Jul 23, 2016 at 10:31
  • In this case, there are 2 titles, what if I have 100 titles, or 1000 titles, How can I handle it? Sorry for not being clear. Commented Jul 23, 2016 at 10:34

1 Answer 1

4

One way is to use a loop to construct an array of observable sequences:

var data = [];
for (var i = 0; i < bodies.length; i++) {
    data.push(this.http.post('/app/books.json', bodies[i], options).map((res:Response) => res.json()));
}

Observable.forkJoin(data).subscribe(data => {
    this.books = data;
});

In this example I assume that you already have the array of bodies constructed dynamically.

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

4 Comments

Correct answer. Thanks.
@Darin, is there a way to avoid partially saved data if some of the post requests fail?
@Yang, yes but you need to have some mechanism on the server to rollback requests. The other option is to send the payloads in a single request to the server and let the server side logic take care of this.
Got it, thank you! I just came across a project using mongodb, which does not provide a better transaction solution. Another motivation is that I tend to implement most of the business logics in frontend instead of backend.

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.