ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
JSON简短响应
{
"hourly_forecast": [
{
"condition": "غائم جزئياً",
"icon": "partlycloudy",
"icon_url": "http://icons.wxug.com/i/c/k/partlycloudy.gif",
"fctcode": "2",
"sky": "30"
}
]
}
代码
weather : any
constructor(private https: HttpClient) {
this.https.get('xxxxxxxxxxxx/q/muscat.json')
.subscribe(data => {
this.weather= data
console.log(this.weather)
})
}
html
<tr *ngFor="let item of weather">
<td>{{item.hourly_forecast.condition}}</td>
</tr>
有什么想法吗?
答案 0 :(得分:3)
<tr *ngFor="let item of weather.hourly_forecast.condition">
<td>{{item}}</td>
</tr>
这将起作用
答案 1 :(得分:2)
您的数据是一个对象,而不是数组。数组包装在对象的.hourly_forecast
字段中:
<tr *ngFor="let item of weather?.hourly_forecast">
<td>{{item.condition}}</td>
</tr>
请确保添加一个?
,以便在数据到达之前不会出错。
答案 2 :(得分:1)
这是有效的示例代码!
var json = {
"hourly_forecast": [{
"condition": "غائم جزئياً",
"icon": "partlycloudy",
"icon_url": "http://icons.wxug.com/i/c/k/partlycloudy.gif",
"fctcode": "2",
"sky": "30"
},
{
"condition": "غائم جزئياً",
"icon": "partlycloudy",
"icon_url": "http://icons.wxug.com/i/c/k/partlycloudy.gif",
"fctcode": "2",
"sky": "30"
}
],
"hourly_forecast2": [{
"condition": "غائم جزئياً",
"icon": "partlycloudy",
"icon_url": "http://icons.wxug.com/i/c/k/partlycloudy.gif",
"fctcode": "2",
"sky": "30"
}]
}
// If you want iterate inside
for (var element in json) {
var data = json[element];
for (var val in data) {
console.log(data[val].condition)
}
}
否则请检查数据是否已正确导入
this.https.get('xxxxxxxxxxxx/q/muscat.json')
.subscribe(data => {
this.weather = data.hourly_forecast;
});
现在它将正常工作
<tr *ngFor="let item of weather">
<td>{{item.hourly_forecast.condition}}</td>
</tr>
答案 3 :(得分:0)
NgFor仅可用于数组。 尝试这样的事情:
*ngFor="let item of weather.hourly_forecast" and <td>{{item.condition}}</td>