Ionic 2: Cannot find a differ supporting object &#

2020-05-01 07:11发布

I am trying to retrieve data from firebase in my service class using:

return this.http.get('https://myfirstfirebaseproject-6da6c.firebaseio.com/products.json')
    .map(res => res.json());

In home.ts, I then subscribe to it using:

        this.productService.fetchProducts()
            .subscribe(data => {
              console.log(data)
              this.products = data;
            });

I output to home.html using:

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

but i keep getting the error

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

I tried looking at similar issues but to no avail. Please help.

1条回答
ら.Afraid
2楼-- · 2020-05-01 07:20

Please check your JSON. https://myfirstfirebaseproject-6da6c.firebaseio.com/products.json It returns an Object not an Array. That is why you cannot use returned data in 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"
    }
}

Try this:

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

In your component.ts:

keys: string[];
...
this.productService.fetchProducts()
            .subscribe(data => {
              console.log(data)
              this.products = data;
              this.keys = Object.keys(this.products);
            });

And modify your onItemClick() accordingly.

查看更多
登录 后发表回答