在模板中显示 json 数据

Displaying json data in a template

我想知道是否有人可以帮助我显示我的数据。

我有一个调用我的 API 的自定义提供程序,一切都很完美。

我使用的页面是 'playing',我的 playing.ts 文件如下所示

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);
            });
    }

}

控制台日志显示如下:

我的 playing.html 文件如下所示

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

我得到的错误如下:

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

我有点困惑,我正在使用 Ionic 2 beta 11

如有任何帮助,我们将不胜感激。

和平!

错误消息非常简单明了。 NgFor 仅适用于数组(或类似数组的可迭代对象)。你不能用它迭代一个对象。
您要迭代的是 data 对象中的 sports 数组,因此解决方案很简单:

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

我找到了答案,以防有人 运行 遇到同样的问题。

在我的提供商中,当我创建一个新的 Promise 和 运行 我的 http get 时,我有以下行

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

我需要将返回的数组名称添加到 res.json(),所以我的修复是按如下方式编辑该行:

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

希望对大家有所帮助。

和平!