Ionic2 Ngfor仅支持数组

我尝试通过http客户端加载一些json,但是当涉及到视图时,我总是会收到此错误:

NgFor only supports binding to Iterables such as Arrays

当我查看console.log输出时,我看到它是一个包含其他对象的对象。 在此处输入图片说明

那就是我的服务代码:

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

然后是我的page.ts构造函数,在其中装载数据:

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

我的page.html ngfor:

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

最后是来自本地主机url的json:

{
  "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"
      }
    ]
  }
}

希望有人知道出什么问题了,这使我发疯。

塞巴费雷拉斯

您的Json应该是[{"title" : ...}, {"title": ...}]因为现在,它不是一个数组,而是一个具有两个名为01的属性对象您是否尝试过像这样更改Json:

[
  {
    "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"
      }
    ]
  }
]

现在您认为:

<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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章