在两个单独的成功 http 请求后触发回调

Egg*_*ggy 4 javascript rxjs typescript angular

我的应用程序在 init 上的根组件从我的服务中调用两个异步函数来获取数据。我想知道在它们都完成后如何调用函数。我正在使用 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();
  }
}
Run Code Online (Sandbox Code Playgroud)

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')
    );
}
Run Code Online (Sandbox Code Playgroud)

Nyp*_*pan 5

一个简单的仍然并行的解决方案是这样的:

let serviceStatus = { aDone: false, bDone: false };

 let getDataA = (callback: () => void) => {
     // do whatver.. 
     callback();
 }

 let getDataB = (callback: () => void) => {
     // do whatver.. 
     callback();
 }

 let bothDone = () => { console.log("A and B are done!");

 let checkServiceStatus = () => {

     if ((serviceStatus.aDone && serviceStatus.bDone) == true)
        bothDone();
 }

 getDataA(() => { 
     serviceStatus.aDone = true;
     checkServiceStatus(); 
});

getDataA(() => { 
     serviceStatus.bDone = true;
     checkServiceStatus(); 
});
Run Code Online (Sandbox Code Playgroud)

我个人使用RxJS来让我摆脱这种棘手的情况,可能值得一看。

编辑:

鉴于实际使用 RxJS 的反馈:

let observable1: Rx.Observable<something>;
let observable2: Rx.Observable<something>;

let combinedObservable = Rx.Observable
    .zip(
        observable1.take(1), 
        observable2.take(1),
        (result1, result2) => {
            // you can return whatever you want here
            return { result1, result2 };
        });

combinedObservable
    .subscribe(combinedResult => {
        // here both observable1 and observable2 will be done.
    });
Run Code Online (Sandbox Code Playgroud)

此示例将并行运行两个 observable,并在它们都完成后将结果合并为一个结果。

  • Angular2 使用 RxJS(并且 http 服务返回一个 Observable)。所以这个问题最好用“如何等待多个 observable 完成?”来表述。 (2认同)