我可以使用以下代码处理来自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
。
答案 0 :(得分:9)
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);