gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:18:44 26 4
gpt4 key购买 nike

我可以使用以下代码处理来自 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);

关于http - 在 Angular2 中同时获取多个 HTTP 资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34301417/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com