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]
      }
    );
  }
Vicheanak
  • 6,444
  • 17
  • 64
  • 98

1 Answers1

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Correct answer. Thanks. – Vicheanak Jul 23 '16 at 10:54
  • @Darin, is there a way to avoid partially saved data if some of the post requests fail? – Yang Apr 11 '17 at 01:45
  • @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. – Darin Dimitrov Apr 11 '17 at 06:00
  • 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. – Yang Apr 11 '17 at 06:40