Vicheanak Vicheanak - 4 months ago 174
AngularJS Question

How to Wait for Angular2 to Handle Dynamic Multiple Http Requests?

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]
}
);
}

Answer

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.

Comments