我正在尝试使用:
从我的服务类中检索数据return this.http.get('https://myfirstfirebaseproject-6da6c.firebaseio.com/products.json')
.map(res => res.json());
在home.ts中,我然后使用以下方式订阅它:
this.productService.fetchProducts()
.subscribe(data => {
console.log(data)
this.products = data;
});
i输出到home.html使用:
<ion-card ion-item *ngFor="let product of products; let i = index" (click)="onItemClick(product)">
<ion-card-header>
{{ product.date | date }}
</ion-card-header>
<ion-card-content>
<ion-card-title>
{{ product.title }}
</ion-card-title>
<p>
{{ product.content }}
</p>
</ion-card-content>
</ion-card>
,但我不断出现错误
错误:找不到类型'对象'的支持对象'[对象对象]。NGFOR仅支持绑定到迭代式的数组。
我尝试查看类似的问题,但无济于事。请帮助。
请检查您的JSON。https://myfirstfirebaseproject-6da6c.firebaseio.com/products.json它返回对象而不是数组。这就是为什么您不能在NGFOR中使用返回的数据。
{
-KiTWPuI_TYt0b_Qi03Y: {
amount: 0,
category: "Baby",
content: "I love cricket",
date: "2017-03-01",
title: "Cricket"
},
-Kid7fghtlxkyrOChQPk: {
amount: "111",
category: "Book",
content: "updated content",
date: "2017-04-01",
title: "Cycling"
},
d9e7545c-90a3-4a57-97ab-ea3bf9171023: {
amount: "12",
category: "Baby",
content: "COnten1",
date: "2017-01-01",
title: "Title2"
}
}
尝试以下操作:
<ion-card ion-item *ngFor="let key of keys; let i = index" (click)="onItemClick(key)">
<ion-card-header>
{{ products[key].date | date }}
</ion-card-header>
<ion-card-content>
<ion-card-title>
{{ products[key].title }}
</ion-card-title>
<p>
{{ products[key].content }}
</p>
</ion-card-content>
</ion-card>
在您的组件中:
keys: string[];
...
this.productService.fetchProducts()
.subscribe(data => {
console.log(data)
this.products = data;
this.keys = Object.keys(this.products);
});
并相应地修改您的onItemClick((。