q.all 用于 angular2 observables

Posted

技术标签:

【中文标题】q.all 用于 angular2 observables【英文标题】:q.all for angular2 observables 【发布时间】:2016-09-07 09:54:42 【问题描述】:

有没有像 q.all 这样的东西来解决 angular2 中的所有 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一起解决,然后做点什么。

【问题讨论】:

【参考方案1】:

你需要.forkJoin 操作符

Observable.forkJoin([observable1,observable2])
       .subscribe((response) => 
          console.log(response[0], response[1]);
       );

你可以用;导入Observable

import Observable from 'rxjs/Rx';

【讨论】:

您是否还知道 $q.all() 调用的其他变体的 RXJS 解决方案,您可以在其中传递对象而不是数组?这是一种更优雅的方法,因为您以后可以通过名称而不是索引来处理 Promise。【参考方案2】:

角度

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

角度 >= 6:

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

【讨论】:

以上是关于q.all 用于 angular2 observables的主要内容,如果未能解决你的问题,请参考以下文章