在 Angular2 中同时获取多个 HTTP 资源

Getting multiple HTTP resources concurrently in Angular2

我可以使用以下代码处理来自 http.get 的单个可观察结果:

http.get('/customers/1')
        .map((res: Response) => res.json())
        .subscribe(customer => this.customer = customer);

现在我有一个像 var list:number[] = [1, 4, 7]; 这样的资源 ID 列表,我希望能够发送对所有资源的请求并将所有已解决的项目分配给我的数组,如 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 加入所有 observables:

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