如何使执行等待forkJoin结果

时间:2017-08-02 11:03:20

标签: angular typescript rxjs

如何让以下代码等待forkJoin执行,以便我可以从bulkRequest返回结果?

  constructor(private http: Http) {
    let results = this.bulkRequest(this.get("https://jsonplaceholder.typicode.com/posts/1"),
      this.get("https://jsonplaceholder.typicode.com/posts/1"),
      this.get("https://jsonplaceholder.typicode.com/posts/1"));

    console.log("results");
  }

  get(url: string): Observable<any> {
    return this.http.get(url).map(response => response.json());
  }

  bulkRequest(...sources: SubscribableOrPromise<any>[]): any[] {
    let results: any[];

    Observable.forkJoin(
        sources
    ).subscribe(response => {
        console.log("responses");
        results = response;
    }, error => {
      console.log("error: " + error.toString());
    },
    () => {
      console.log("finally");
    });

    return results;
  }

目前,我获得了以下控制台输出,results变量为undefined

results
responses
finally

observable执行,如果我在console.log("results")行放置一个断点,我会在网络标签中看到它们全部为Pending

Plnkr:http://plnkr.co/edit/2wb72kw7S3wYUUwwwi8h?p=preview

2 个答案:

答案 0 :(得分:2)

return Observable.forkJoin( ...

并删除

return results;

没有办法等待观察者。 您需要订阅返回的observable,并调用bulkRequest()

答案 1 :(得分:1)

返回Observable而不是results变量:

public bulkRequest(...sources: SubscribableOrPromise<any>[]): any[] {
  return Observable.forkJoin(sources);
}

查看更新后的演示:http://plnkr.co/edit/7DPBjeha0p2vdj4QjN5V?p=info