Angular2可观察对象的q.all

24

在Angular2中是否有类似于q.all的东西可以解决所有HTTP API请求?

在Angular1中,我可以这样做:

var promises = [api.getA(),api.getB()];
$q.all(promises).then(function(response){
    // response[0]  --> A
    // response[1]  --> B
})
在Angular2中,http模块返回Observable。
api.getA().subscribe(A => {A})
api.getB().subscribe(B => {B})

但我希望能够同时解决A和B,然后再做些什么。

2个回答

33
你需要使用.forkJoin操作符。
Observable.forkJoin([observable1,observable2])
       .subscribe((response) => {
          console.log(response[0], response[1]);
       });

您可以使用以下方式导入 Observable

import {Observable} from 'rxjs/Rx';

4
你是否也知道RXJS解决方案,适用于$q.all()的另一种调用变体,其中你可以传递一个对象而不是数组?这是更优雅的方法,因为你稍后可以通过名称而不是索引来访问Promise。 - ŁukaszBachman

1
Angular < 6:
import {Observable} from 'rxjs/Observable';
    ...
    return Observable.forkJoin(
        this.http.get('someurl'),
        this.http.get('someotherurl'));

Angular >= 6:

import {forkJoin} from 'rxjs';
...
return forkJoin(
    this.http.get('someurl'),
    this.http.get('someotherurl'));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接