如何让以下代码等待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
。
答案 0 :(得分:2)
return Observable.forkJoin( ...
并删除
return results;
没有办法等待观察者。
您需要订阅返回的observable,并调用bulkRequest()
。
答案 1 :(得分:1)
返回Observable而不是results
变量:
public bulkRequest(...sources: SubscribableOrPromise<any>[]): any[] {
return Observable.forkJoin(sources);
}