[英]Angular 2 chain http requests with iterable array and merge resutls
New to angular and confused with the flatMap
function. 角度的flatMap
,与flatMap
函数混淆。
export interface IProduct {
productId: number;
productName: string;
versionUrl: string;
versionObj: any;
}
First HTTP request returns array of IProduct
objects. 第一个HTTP请求返回IProduct
对象的数组。 Make HTTP request for each product using the versionUrl
from the product object and map the resulting object to product.versionObj
. 使用产品对象中的versionUrl
对每个产品进行HTTP请求,并将结果对象映射到product.versionObj
。
product.versionObj
==> should be mapped to the result of each product's HTTP request. product.versionObj
==>应该映射到每个产品的HTTP请求的结果。
getAllProductsWithAddlInfo(): Observable<IProduct[]> {
return this._http.get('products.json')
.flatMap((response: Response) => response.json())
.flatMap((product: IProduct) => this._http.get(product.versionUrl),
(product: IProduct, resp) => resp.json())
products: IProduct[];
/*
I would like to get an array of products with the additional info object
mapped to versionObj from the http call for each product
*/
ngOnInit(): void {
this._productService.getAllProductsWithAddlInfo()
.subscribe(
products => this.products = products,
error => this.errorMessage = <any>error);
console.log(this.products);
}
You could use Observable.toArray()
: 您可以使用Observable.toArray()
:
getAllProductsWithAddlInfo(): Observable<IProduct[]> {
return this._http.get(
'products.json'
).flatMap(
(response: Response) => response.json()
).flatMap(
(product: IProduct) => this._http.get(product.versionUrl),
(product: IProduct, resp) => {
product.versionObj = resp.json();
return product;
// or simply: (product.versionObj = resp.json(), product)
}
).toArray();
}
But change the debug function (at ngOnInit()
) to print after the next event (otherwise it will print before the observer emmits any values): 但是将调试功能(在ngOnInit()
)更改为在下一个事件之后打印(否则它将在观察者发出任何值之前打印):
ngOnInit(): void {
this._productService.getAllProductsWithAddlInfo()
.subscribe(
products => {
this.products = products;
console.log('Products: ', this.products); // console.log() move to here
},
error => this.errorMessage = <any>error
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.