我可以http.get
使用以下代码处理单个可观察的结果:
http.get('/customers/1') .map((res: Response) => res.json()) .subscribe(customer => this.customer = customer);
现在我有一个资源ID列表var list:number[] = [1, 4, 7];
,我希望能够发送所有资源的请求,并将所有已解析的项目分配给我的数组customers => this.customers = customers
.
Rx.Observable.forkJoin可以做到这一点.
首先导入Obserable&forkJoin:
import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/forkJoin';
或全部导入
import {Observable} from 'rxjs/Rx';
现在加入所有可观察者forkJoin
:
// a set of customer IDs was given to retrieve var ids:number[] = [1, 4, 7]; // map them into a array of observables and forkJoin Observable.forkJoin( ids.map( i => this.http.get('/customers/' + i) .map(res => res.json()) )) .subscribe(customers => this.customers = customers);