q.all for angular2 observables

六月ゝ 毕业季﹏ 提交于 2019-12-03 14:55:12

问题


is there something like q.all to resolve all http api requests in angular2?

In angular1, I can do something like this:

var promises = [api.getA(),api.getB()];
$q.all(promises).then(function(response){
    // response[0]  --> A
    // response[1]  --> B
})

In angular2, the http module returns Observable,

api.getA().subscribe(A => {A})
api.getB().subscribe(B => {B})

But I want to resolve A and B together, then do something.


回答1:


You will need the .forkJoin operator for that

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

You can import the Observable with;

import {Observable} from 'rxjs/Rx';



回答2:


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'));


来源:https://stackoverflow.com/questions/37172093/q-all-for-angular2-observables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!