Angular *ngFor Array of Objects returning [ERROR: Cannot find a differ supporting object]

点点圈 提交于 2019-12-10 11:45:43

问题


I am trying to display in HTML a list of data as follows:

Home.ts:

this.key = 0
objects = {} // The correct setting was objects = [] thanks!

snapshot.forEach(doc => {

          this.objects[this.key] = {
            firstname: doc.id,
            lastname: doc.data().lastname,
            age: doc.data().age
          }

          this.key=this.key+1;
        }

This results in the following when displayed in JSON:

console.log(JSON.stringify(this.objects));

// RESULT OF THE CONSOLE:

{
 "0":
    {
        "firstname":"james",
        "lastname":"bond",
        "age":"87"
    },

 "1":
    {
        "firstname":"alex",
        "lastname":"tali",
        "age":"59"
    }
 } 

Now when i use:

console.log(this.objects[0].firstname);

// The Result displays:
james

Which is the correct behavior! However when trying to display the list in HTML using the *ngFor it is giving me the Error: Cannot find a differ supporting object.

Here is my code in Home.html HTML/IONIC:

    <ion-grid>
      <ion-row>
        <ion-col col-4>First Name</ion-col>
        <ion-col col-4>Last Name</ion-col>
        <ion-col col-4>Age</ion-col>
      </ion-row>
      <ion-row>
        <ion-col col-4 *ngFor="let firstname of objects; let i = index">{{ objects[i].firstname }}</ion-col>
        <ion-col col-4 *ngFor="let lastname of objects; let i = index">{{ objects[i].lastname }}</ion-col>
        <ion-col col-4 *ngFor="let age of objects; let i = index">{{ objects[i].age }}</ion-col>
      </ion-row>
    </ion-grid> 

Any how I can implement the above correctly? logically it should be working just fine! as similar console.log gives a correct result. While doing a LOT of research i stumbled upon this topic: https://github.com/angular/angular/issues/6392

Which to be honest I'm nor sure if it fits my problem or not.

Thanks a lot!


回答1:


As the error says objects should be an array of objects, according to your JSON its an object of objects. you need to have proper JSON array, or convert to array of objects.

console.log(JSON.stringify(this.global.objects));


来源:https://stackoverflow.com/questions/47230070/angular-ngfor-array-of-objects-returning-error-cannot-find-a-differ-supportin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!