我知道您可以通过调用forkJoin方法来使用Observable来等待多个http请求完成,如下所示:
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]
}
);
}
然而,在我的情况下,我有多个http帖子,它们是动态的,如下面的代码,有2个标题,如果我有100或1000个标题。我该如何处理这样的动态帖子请求?请建议。
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]
}
);
}
答案 0 :(得分:3)
一种方法是使用循环来构造可观察序列的数组:
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;
});
在这个例子中,我假设你已经动态构建了bodies
数组。