希望大家帮帮我。我们的计划是使用 ngFor 循环显示保存在 .json 文件中的数据。
到目前为止,我的代码总是遇到以下错误:
Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
我已经研究过并且知道我必须使用 Pipes 来修复它。但我不知道它是如何工作的,因为我是 Angular 的新手。
这就是我加载 JSON 并将其分配给临时变量的方式:
ngOnInit(): void {
this.http.get('assets/tempdata.json').subscribe(data => {
//console.log(data);
this.temps = data;
});
}
这里是我要显示的 .html 文件的一部分:
<mat-card-content>
<mat-list>
<mat-list-item *ngFor="let temp of temps">
<i class="{{temp.icon}}"></i><p>{{temp.temp}}{{temp.room}}</p>
</mat-list-item>
</mat-list>
</mat-card-content>
这是我要显示的 .JSON 文件:
{
"temperature": [
{
"temp": "4°",
"room": " Outside",
"icon": 4
},
{
"temp": "21°",
"room": " Livingroom",
"icon": 21
},
{
"temp": "24°",
"room": " Bedroom",
"icon": 24
},
{
"temp": "11°",
"room": " Basement",
"icon": 11
}
]
}
如果有人能帮我解决这个问题就太好了。任何提示或更多提示都是有帮助的。非常感谢!
最佳答案
ngFor 遍历表,而不是对象。错误告诉你。
您的 JSON 是一个对象(它以 {
开头,而不是 [
)。
如果你想迭代它,你要么必须将它更改为数组,要么你必须迭代键。为此:
this.keys = Object.keys(data);
在您的 HTML 中:
<mat-list-item *ngFor="let key of keys">
您将通过
访问您的数据{{ temps[key] }}
关于json - 使用 ngFor-Loop (Angular) 显示 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47772718/