0
votes

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
More than likely, what you are getting in the data from the API call is not an array, but an object. Use console.log(data) to see what it looks like, then make any changes you need to make.R. Richards
Hi Richard, I get an object. Should I manually convert the object to array on my own?Jason
Is there an array in the object somewhere? If there is, use it. If there is not, convert it somehow, or don't iterate in the template.R. Richards

1 Answers

3
votes

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.