如何等待Angular2处理动态多个Http请求? [英] How to Wait for Angular2 to Handle Dynamic Multiple Http Requests?

查看:51
本文介绍了如何等待Angular2处理动态多个Http请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道您可以通过调用forkJoin方法来使用Observable,以等待多个http请求完成,如下所示:

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

但是,就我而言,我有多个http帖子,它们像下面的代码一样是动态的,有2个标题,如果我有100个或1000个标题,该怎么办?如何处理此类动态帖子请求?请提出建议.

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

推荐答案

一种方法是使用循环来构造可观察序列的数组:

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

在此示例中,我假设您已经具有动态构造的 body 数组.

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

这篇关于如何等待Angular2处理动态多个Http请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆