BigJobbies
BigJobbies

Reputation: 4033

Displaying json data in a template

I was wondering if someone could help me out displaying my data.

I have a custom provider which calls my API, which all works perfect.

The page im working with is 'playing' and my playing.ts file looks like the following

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { PlayingService } from '../../providers/playing-service/playing-service';

@Component({
  templateUrl: 'build/pages/playing/playing.html',
})

export class PlayingPage {

    sports: any;

    constructor( private playing: PlayingService, private navCtrl: NavController ) {
        this.loadSports();
    }

    loadSports() {
        this.playing.getAllSports()
            .then(data => {
                this.sports = data;
                console.log(data);
            });
    }

}

The console log displays the following:

array description here My playing.html file looks like the following

<ion-content padding class="playing-screen">
  <ion-list>
    <ion-item *ngFor="let sport of sports" >
       <h3>{{sport}}</h3>
     </ion-item>
   </ion-list>
</ion-content>

The error im getting is as follows:

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

Im a little confused, im working with Ionic 2 beta 11

Any help would be greatly appreciated.

Peace!

Upvotes: 1

Views: 2100

Answers (2)

BigJobbies
BigJobbies

Reputation: 4033

I figured out the answer incase anyone runs into the same issue.

In my provider, when i create a new Promise and run my http get, i had the following line

.map(res => res.json())

I needed to add the returned array name to the res.json(), so my fix was to edit the line as follows:

.map(res => res.json().sports)

I hope this can help someone.

Peace!

Upvotes: 0

Yaron Schwimmer
Yaron Schwimmer

Reputation: 5357

The error message is pretty straight-forward. NgFor only works for arrays (or array-like iterables). You cannot iterate an object with it.
What you want to iterate is the sports array inside your data object, so the solution is easy:

loadSports() {
    this.playing.getAllSports()
        .then(data => {
            this.sports = data.sports || []; //for safety
        });
}

Upvotes: 2

Related Questions