【发布时间】:2019-02-28 16:13:56
【问题描述】:
我在控制台中收到此错误,Cannot read property '0' of undefined 但我仍然按预期获得了结果。
这是我的 HTML 代码
<div class="col-md-3">
<div class="slider-product">
<a href="#">
<img src="{{featureProducts[0].img_path}}" alt="Image" style="max-width:100%;">
<span class="tag">{{featureProducts[0].cat_name}}</span>
<div>
<a class="title">{{featureProducts[0].name}}</a>
</div>
<div class="price">
<i class="fa fa-inr"></i> {{featureProducts[0].min_price}}
</div>
</a>
</div>
</div>
这是打字稿文件中的函数
getFeatureProducts(){
this.httpClient.get(this.baseUrl+`/getFeatureProducts`)
.subscribe(
(data:any[]) => {
if(data.length) {
this.featureProducts = data;
}else{
this.featureProducts = null;
}
}
)}
featureProducts 在类中声明为
featureProducts: any;
我知道这个问题可以解决,就像我可以使用多个变量,如下所示
在打字稿中
imgpath0 = this.featureProducts[0].imgPath;
并且在html中直接使用这个变量作为
{{imgPath0}}
但这不是更好的方法,因为我有很多属性要在 html 中显示,我不能在 ts 中声明这么多变量。
注意: 我不想在 html 中使用 'for' 循环。相反,我需要像我们通常在 JSON 中那样获取属性。
【问题讨论】:
标签: json typescript codeigniter angular6