我尝试通过http客户端加载一些json,但是当涉及到视图时,我总是会收到此错误:
n++
当我查看console.log输出时,我发现它是一个包含其他对象的对象。
这就是我的服务代码:
NgFor only supports binding to Iterables such as Arrays
然后我的page.ts构造函数加载了数据:
@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.html ngfor:
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')
);
}
最后我的json来自localhost url:
<ion-card *ngFor="let data of displayData">
</ion-card>
希望有人知道什么是错的,因为这让我发疯。
答案 0 :(得分:4)
你的Json应该是[{"title" : ...}, {"title": ...}]
,因为现在它不是数组而是对象,有两个名为 0 <的属性/ em>和 1 。您是否尝试过像这样更换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>