#angular #ionic4
#angular #ionic4
Вопрос:
я пытаюсь получить данные о погоде в формате json для wunderground api, используя ionic 4. При попытке запустить этот код я получил ошибку 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>
пожалуйста, есть идеи?
Комментарии:
1. Вы можете попробовать что-то вроде этого: *ngFor=»пусть элемент weather.hourly_forecast» и <td>{{item.condition}}</td>
Ответ №1:
<tr *ngFor="let item of weather.hourly_forecast.condition">
<td>{{item}}</td>
</tr>
Этот будет работать
Комментарии:
1. проверьте jsoneditoronline.org/?id=aa8b74650bf34bfda07d68ebb7180e62
2. *ngFor=»пусть элемент weather.hourly_forecast.condition», потому что это массив, поэтому вы можете выполнить цикл через это
Ответ №2:
Ваши данные — это объект, а не массив. Массив заключен в .hourly_forecast
поле объекта:
<tr *ngFor="let item of weather?.hourly_forecast">
<td>{{item.condition}}</td>
</tr>
Обязательно добавьте ?
, чтобы не получить ошибку до поступления данных.
Ответ №3:
Вот пример кода, который работает!.
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>
Ответ №4:
ngFor может использоваться только в массивах. Попробуйте что-то вроде этого:
*ngFor="let item of weather.hourly_forecast" and <td>{{item.condition}}</td>