【问题标题】:q.all for angular2 observablesq.all 用于 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一起解决,然后做点什么。

【问题讨论】:

    标签: angular combinations observable subscribe


    【解决方案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'));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-29
      • 1970-01-01
      • 1970-01-01
      • 2016-08-18
      • 2016-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多