Arrays *NgFor过自定义JSON类别文件未呈现
我的资产有一个简单的结构:Arrays *NgFor过自定义JSON类别文件未呈现,arrays,json,angular,http,Arrays,Json,Angular,Http,我的资产有一个简单的结构: [ { "categories": [ { "name": "Fruits" }, { "name": "vegetables" }, { "name": "Meat" } ] } ] 我的数据服务(带有两个JSON调用): } 主页HTML:(已编辑) 两个日志的快照: 类别.
[
{
"categories": [
{
"name": "Fruits"
},
{
"name": "vegetables"
},
{
"name": "Meat"
}
]
}
]
我的数据服务(带有两个JSON调用):
}
主页HTML:(已编辑)
两个日志的快照:
类别.json不直接包含对象,而是包含一个数组,在父级有一个属性元素
类别
。试试下面的方法
this.dataService.getCategories().subscribe(
数据=>{
this.categories=数据[0]['categories'];
控制台日志(数据);
}
);
更新:forkJoin
合并观测值
如果要同时订阅多个观测值,可以使用RxJSforkJoin
组合它们。我怀疑这会解决产品
对象的问题,但它更优雅,不会影响机会
从'rxjs'导入{forkJoin};
恩戈尼尼特(){
分叉连接({
类别:this.dataService.getCategories(),
产品:this.dataService.getProducts(),
})
.订阅(
响应=>{
//句柄响应
this.categories=response.categories[0]['categories'];
this.products=response.products[0]['products'];
},
错误=>{//句柄错误}
);
}
更新:products.json
issue
products.json
文件中似乎存在潜在的打字错误。关键是产品:
。实际上,它应该是产品
这是一个初级问题,但实际上我被卡住了……我在另一个JSON上也遇到了同样的问题。这没有任何意义,因为结构是相同的,我应用了与您建议的相同的响应!请在问题中发布JSON。我将为您编辑som。我不明白为什么它不起作用。您是否收到任何错误消息或数据未显示?请查看控制台日志中的数据结构。另外,您可能需要将*ngFor
指令从
标记移动到
标记。
getCategories() {
return this.http.get<any>('./assets/categories.json')
}
getProducts() {
return this.http.get<any>('./assets/products.json')
}
ngOnInit(): void {
this.dataService.getCategories().subscribe(data=>{
this.categories=data[0]['categories'] -> this works!!
console.log(data)
})
this.dataService.getProducts().subscribe(data=>{
this.products=data[0]['products']
console.log(data)
})
<div class="col-md-4" >
<div class="list-group" style="color:black">
<a
*ngFor="let c of categories"
routerLink='/home'
[queryParams]="{categories:c.name}"
class="list-group-item list-group-item-action"
[class.active]='categories===c.name'>
{{c.name}}
</a>
</div>
</div>
<div class="col-md-8" >
<ul class="list-group" *ngFor="let p of products">
<li class="list-group-item">
{{p.name}}
</li>
</ul>
</div>
[
{
"products:": [
{
"id": "1",
"name": "Apple",
"price": "free",
"category": "Fruits"
},
{
"id": "5",
"name": "Grass",
"price": "Free",
"category": "Vegetabes"
},
{
"id": "6",
"price": "Free",
"category": "Vegetabes"
}
]
}
]