我有两个API api / resource / Item返回
{data: [
{name: "BE106359"},
{name: "NDBKR5050"}
]}
和项目详细信息api / resource / Item / {name}返回
{
data: {
net_weight: 0,
max_discount: 0,
item_name: "NEC | BE106359 | CD-PRTA - ISDN PRI TRUNK BLADE, SV8xxx",
website_warehouse: "Stores - CT",
default_material_request_type: "Purchase",
disabled: 0,
name: "BE106359"
......
}}
我的angular2代码迭代细节,但打印未定义的值,因此无法在我的HTML模板上获得任何值
@Injectable()
export class ProductsService {
getProductDetails() {
return this.http.get("https://domain/api/resource/Item")
.map(
p => {
let products = p.json().data;
products.forEach(m =>
this.http.get('https://domain/api/resource/Item/'+ m.name)
.map(details=> details.json())
.subscribe(details => details.data) // <-- get values when trying to console print out
);
});
}}
//calling service from component
export class ProductsComponent implements OnInit {
products;
constructor(private service: ProductsService) {
this.service.getProductDetails().subscribe(products => this.products = products); // <---- console.log(products) print undefined value
}}
答案 0 :(得分:0)
这解决了我所需要的所有问题mergeMap
getProductDetails() {
let Products: any[] = [];
return this.http.get('https://domain/api/resource/Item')
.map(res => res.json().data)
.mergeMap(list => list)
.mergeMap(name => {
return this.http.get("https://domain/api/resource/Item/" + name['name'])
})
.map(res => {
Products.push(res.json().data)
{ return Products; }
})
}
//then call it from my component
this.service.getProductDetails().subscribe(res=>this.products= res );