新角色与flatMap
函数混淆。
export interface IProduct {
productId: number;
productName: string;
versionUrl: string;
versionObj: any;
}
第一个HTTP请求返回IProduct
个对象的数组。
使用产品对象中的versionUrl
为每个产品发出HTTP请求,并将生成的对象映射到product.versionObj
。
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);
}
答案 0 :(得分:0)
您可以使用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();
}
但是更改调试功能(在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
);
}