我一直在尝试使用这个JSON文件
[
[
{
"category": "Bags",
"productData": [
{
"id": 1000,
"name": "Trolley backpack",
"short description": "short description",
"long description": "LONG DESCRIPTION",
"image": "../../assets/images/catalogue/bags/trolleyBackpack.png"
}
]
},
{
"productData": [
{
"id": 1001,
"name": "Laptop bag",
"short description": "short description",
"long description": "LONG DESCRIPTION",
"image": "../../assets/images/catalogue/bags/laptopBag.png"
}
]
}
],
[
{
"category": "Eco",
"productData": [
{
"id": 1100,
"name": "Bamboo Pen drive",
"short description": "short description",
"long description": "LONG DESCRIPTION",
"image": "../../assets/images/catalogue/eco/bamboo-pendrive.png"
}
]
},
{
"productData": [
{
"id": 1101,
"name": "Bamboo tabletop items",
"short description": "short description",
"long description": "LONG DESCRIPTION",
"image": "../../assets/images/catalogue/bags/bamboo-tabletop.png"
}
]
}
]
]
字符串
我创建了一个服务并使用了http.get。
Productinfo: any = []
constructor(private service: DataStorageService) {}
ngOnInit() {
this.service.GetProductDetails().subscribe(data => {
this.Productinfo = data;
})
}
型
但是,我无法在app.component.html中访问此数据
<div class="container">
<div class="row row-cols-sm-4 g-5">
<div class="col-sm-6 col-md-4 d-flex justify-content-center col-lg-3" *ngFor="let products of Productinfo.productData">
<div
class="card card-cover h-100 overflow-hidden text-white bg-white rounded-5 shadow-lg" *ngIf="">
<img src="{{products.image}}" style="object-fit: cover;">
<div class="d-flex flex-column ps-3 pe-5 fontName text-light text-shadow-1 h-100"
style="position: absolute;">
<h2 class="pt-5 mt-5 mb-4 display-6 lh-1 fw-bold"
style="position: relative;">
{{products.name}}
</h2>
<img
src="../../../assets/images/bonjour-logo.png"
alt="Logo"
width="32"
height="32"
class="rounded-circle border border-dark bg-dark"
style="position: absolute; bottom: 15px;"
/>
</div>
</div>
</div>
型
使用Productinfo.productData
的解决方案似乎不起作用。我应该访问TS文件中的productData数组吗?
我还希望能够根据类别有条件地显示数据。我认为 *ngIf是这里的方法,但我不确定。有更好的方法吗?
谢谢您的支持:)
3条答案
按热度按时间dly7yett1#
你的思路是对的。但是,你的HTML模板似乎有点小误会。
您需要先遍历外部数组,然后再遍历内部数组,以访问各个产品。
字符串
对于基于类别的条件渲染,您可以以类似的方式使用
ngIf
。例如:型
ee7vknir2#
你的JSON包含一个数组,里面有另一个数组,里面有字段为“category”和“productData”的对象。因此,你应该首先循环包含对象的数组。然后,一旦你有了上面提到的字段的对象列表,你可以使用for循环来遍历productData列表。我认为你需要接口来实现这一点。
字符串
hfsqlsce3#
修复JSON结构:
字符串
我想这是你所期望的结构。