Ali Ghassan
Ali Ghassan

Reputation: 1180

Angular get arrays form object using *ngFor

I have following JSON struncture:

{
  "vt1hourlyForecast": {
    "processTime": [
      "2019-08-23T13:00:00+0300",
      "2019-08-23T14:00:00+0300",
      "2019-08-23T15:00:00+0300"
    ],
    "temperature": [
      43,
      44,
      44
    ],
    "icon": [
      34,
      34,
      32
    ]
  }
}

l am try to get those arrays above from vt1hourlyForecast object using NgFor , but l get error

error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

html

    <ion-item *ngFor="let item of hourly">
    <div style="direction: rtl;margin-inline-end: auto;">
      <div>{{item.vt1hourlyForecast.processTime | date:'h:mm a'}}</div>
      <div>
        {{item.vt1hourlyForecast.phrase}} ,
        درجة الحرارة : °{{item.vt1hourlyForecast.temperature}}
      </div>
    </div>
    <ion-thumbnail slot="end">
      <img src="assets/icon/{{item.vt1hourlyForecast.icon}}.png">
    </ion-thumbnail>
  </ion-item>

Code

 this.http.get("xxxxxxxxx")
        .subscribe(data => {

          this.hourly = data


          console.log("forecast " + this.hourly)
        })

There is any way to get those arrays using NgFor please ?

Upvotes: 2

Views: 63

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115222

Actually you need to iterate over one of the internal array and get other value based on index currently you are trying to iterate over object which is not iterable.

<ng-container *ngIf="hourly && hourly.vt1hourlyForecast"> <!-- check it's defined -->
<ion-item *ngFor="let time of hourly.vt1hourlyForecast.processTime;let i = index">
<div style="direction: rtl;margin-inline-end: auto;">
  <div>{{time | date:'h:mm a'}}</div>
  <div>
    {{hourly.vt1hourlyForecast.phrase[i]}} ,
    درجة الحرارة : °{{hourly.vt1hourlyForecast.temperature[i]}}
  </div>
</div>
<ion-thumbnail slot="end">
  <img src="assets/icon/{{hourly.vt1hourlyForecast.icon[i]}}.png">
</ion-thumbnail>
</ion-item>
</ng-container>

Upvotes: 1

Andreas
Andreas

Reputation: 76

You should re-arrange the json to reflect an array structure as

[
    {
        "processTime": "2019-08-23T13:00:00+0300",
        "temperature": 43,
        "icon": 34
    },
    {
        "processTime": "2019-08-23T14:00:00+0300",
        "temperature": 44,
        "icon": 34
    },
    {
        "processTime": "2019-08-23T15:00:00+0300",
        "temperature": 44,
        "icon": 32
    }
]

The corresponding html could be like this:

<ion-item *ngFor="let item of hourly">
    <div style="direction: rtl;margin-inline-end: auto;">
        <div>{{item.processTime | date:'h:mm a'}}</div>
        <div>
            درجة الحرارة : °{{item.temperature}}
        </div>
    </div>
    <ion-thumbnail slot="end">
        <img src="assets/icon/{{item.icon}}.png">
    </ion-thumbnail>
</ion-item>

Upvotes: 0

Related Questions