【发布时间】:2016-03-07 05:13:13
【问题描述】:
我的应用程序的根组件在初始化时从我的服务中调用两个异步函数来获取数据。我想知道它们都完成后如何调用一个函数。我正在使用 angular 2.0.0-alpha.44 和 typescript 1.7.3
import {Component, OnInit} from 'angular2/angular2';
import {ServiceA} from './services/A';
import {ServiceB} from './services/B';
@Component({
selector: 'app',
template: `<h1>Hello</h1>`
})
export class App {
constructor(
public serviceA: ServiceA,
public serviceB: ServiceB
) { }
onInit() {
// How to run a callback, after
// both getDataA and getDataB are completed?
// I am looing for something similar to jQuery $.when()
this.serviceA.getDataA();
this.serviceB.getDataB();
}
}
serviceA.getDataA 和 serviceA.getDataB 是简单的 http get 函数:
// Part of serviceA
getDataA() {
this.http.get('./some/data.json')
.map(res => res.json())
.subscribe(
data => {
// save res to variable
this.data = data;
},
error => console.log(error),
// The callback here will run after only one
// function is completed. Not what I am looking for.
() => console.log('Completed')
);
}
【问题讨论】:
-
也许
$q.all会有所帮助。这是nice answer。
标签: javascript angular typescript rxjs