1

我尝试通过 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>

最后是来自 localhost 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"
      }
    ]
  }
}

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

4

1 回答 1

4

你的 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>
于 2016-07-12T09:47:59.810 回答