【发布时间】:2018-09-17 03:46:06
【问题描述】:
我正在使用 Angular4 应用程序,在此我试图在我的组件文件中接收 json 数据。但我得到未定义的响应。
Json 结构
服务文件
get_New_Products():Observable<Products[]>{
this.productServiceURL = `http://localhost:abc/api/data/Get_Product`;
return this.http.get<Products[]>(this.productServiceURL);
}
在服务文件中,我使用以下代码行得到了结果
console.log(data); //output : Array of data
具体数据
console.log(data[0]['PRODUCT_NAME']); // output : iPhone
组件文件
ngOnInit() {
this.CartdataService.get_New_Products();
this.CartdataService.get_New_Products()
.subscribe(
data => {
this.products_Id = data['PRODUCT_ID'];
this.product_Name = data['PRODUCT_NAME'];
this.products_Price = data['PRODUCT_PRICE'];
this.products_Image=data['PRODUCT_IMAGE']
this.products_Image_Onhover=data['PRODUCT_IMAGE_ONHOVER']
console.log(this.product_Name);
});
}
在这里我无法访问数据。我想将所有 PRODUCT_ID、PRODUCT_NAME..etc 绑定在一个变量中。我认为我尝试获取数据的方式是错误的。
我必须在这几行中施展魔法,
this.products_Id = data['PRODUCT_ID'];
this.product_Name = data['PRODUCT_NAME'];
this.products_Price = data['PRODUCT_PRICE'];
this.products_Image=data['PRODUCT_IMAGE']
this.products_Image_Onhover=data['PRODUCT_IMAGE_ONHOVER']
模型文件
export interface Products{
PRODUCT_ID :string[];
PRODUCT_NAME : string[];
PRODUCT_PRICE : string[];
PRODUCT_IMAGE : string[];
PRODUCT_IMAGE_ONHOVER : string[];
}
请帮我解决这个问题。
【问题讨论】:
-
能否提供整个组件代码。您可能没有正确注入服务。
-
很确定您将不得不迭代您的
。你确实要求接收它们的数组。 -
如果您正在获取 json 对象数组,您应该使用响应数组上的映射函数映射到组件中的数组。见帖子:stackoverflow.com/questions/40256658/…
-
@MirkoAcimovic。 - 该帖子指的是旧的 HTTP API。现在使用 v4,我们应该假设 HttpClient 现在默认需要 JSON。问题中的 OP 确认了这一点 - 服务正确接收了数据。
-
您可以在组件端使用 console.log(data) 并将其附加到问题中吗? @尼克森
标签: angular