Zero Zero - 4 months ago 29
JSON Question

Ionic2 Ngfor only supports array

im try to load some json via http client, but when it comes to the view i always get this error:

NgFor only supports binding to Iterables such as Arrays


When i look at the console.log output i see that it is an object with other objects in it. enter image description here

Thats my service code:

@Injectable()
export class DataService {
data: any;

constructor(private http: Http) {
this.data = null;
}

load() {

// We're using Angular Http provider to request the data,
// then on the response it'll map the JSON data to a parsed JS object.
// Next we process the data and resolve the promise with the new data.
return this.http.get('http://localhost:3000/db') //json url
.map(res => res);
}
}


Then my page.ts constructor where the data is loaded :

constructor(private nav:NavController, navParams:NavParams, http:Http, public service:DataService) {
this.service.load().subscribe (
response => {
this.displayData=response;
console.log(this.displayData);
},
error => console.log ('error in download')
);
}


My page.html ngfor:

<ion-card *ngFor="let data of displayData">
</ion-card>


And finally my json from the localhost url:

{
"0": {
"title": "Erreichbarkeit",
"items": [
{
"name": "1",
"value": "a"
},
{
"name": "2",
"value": "b"
},
{
"name": "3",
"value": "c"
}
]
},
"1": {
"title": "Erreichbarkeit 2",
"items": [
{
"name": "1",
"value": "g"
},
{
"name": "2",
"value": "f"
},
{
"name": "3",
"value": "e"
}
]
}
}


Hope somebody knows whats wrong cause this drives me crazy.

Answer

Your Json should be [{"title" : ...}, {"title": ...}] because right now, it's not an array but an object with two properties called 0 and 1. Have you tried with changing the Json like this:

[
  {
    "title": "Erreichbarkeit",
    "items": [
      {
        "name": "1",
        "value": "a"
      },
      {
        "name": "2",
        "value": "b"
      },
      {
        "name": "3",
        "value": "c"
      }
    ]
  },
  {
    "title": "Erreichbarkeit 2",
    "items": [
      {
        "name": "1",
        "value": "g"
      },
      {
        "name": "2",
        "value": "f"
      },
      {
        "name": "3",
        "value": "e"
      }
    ]
  }
]

And now in your view:

<ion-card *ngFor="let data of displayData">

    <ion-card-header>{{data.title}}</ion-card-header>   

    <ion-card-content >
        <p *ngFor="let item of data.items">{{item.name}} : {{item.value}}</p>
    </ion-card-content>

</ion-card>

Working plunker.