Angular 2同步问题 - 完成2个异步调用后调用函数

时间:2017-11-10 21:05:04

标签: angular typescript asynchronous synchronization

我有一个场景,我需要在函数A和B之后调用函数C,它们是异步执行的。函数A和B从服务器检索数据,稍后我需要调用函数C,但每个函数都是独立的。

我可以链接它们,调用A然后在检索数据后调用B,最后在检索B的数据后调用C.但是由于A和B不相互依赖,因此运行更有意义它们并行,然后在完全运行C之后。

这里有一些示例代码:

ngOninit() {
    this.mySrv.getSomeStuff() // Returns an observable
        .subscribe(data => this.stuff = data);
    this.mySrv.getOtherStuff().subscribe(data => this.other = data);
    // I need both data to execute the next function
    this.mySrv.doSomething(this.stuff, this.other)
            .subscribe(data => {/* do something */});
}

1 个答案:

答案 0 :(得分:2)

您可以使用Observable.forkJoin作为前两个请求,它们以并行方式运行它们。然后使用flatMapmergeMap),您可以根据之前的结果执行请求,然后最终订阅。所以像这样:

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';
import 'rxjs/add/operator/mergeMap';

// ...

ngOnInit() {
  Observable.forkJoin(this.mySrv.getSomeStuff(), this.mySrv.getOtherStuff())
    .flatMap(data => {
      console.log(data[0]) // result of 'getSomeStuff()'
      console.log(data[1]) // result of 'getOtherStuff()'
      return this.mySrv.doSomething(data[0], data[1])
    })
    .subscribe(data => {
      console.log(data) // result of 'doSomething()'
    })
}
相关问题