角* ngFor返回对象的数组[错误:无法找到一个不同的支持对象]

角* ngFor返回对象的数组[错误:无法找到一个不同的支持对象]

问题描述:

我想在HTML如下显示的数据列表:角* ngFor返回对象的数组[错误:无法找到一个不同的支持对象]

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

这导致当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" 
    } 
} 

现在,当我使用:

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

// The Result displays: 
james 

这是正确的行为! 但是,当试图使用* ngFor在HTML中显示列表时,它给了我错误:无法找到不同的支持对象。

这是我在Home.html中HTML /离子代码:

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

任何我怎么能正确地执行上面的?从逻辑上讲,它应该工作得很好!作为类似的console.log给出了一个正确的结果。 虽然做了大量的研究,我偶然发现了这个话题:https://github.com/angular/angular/issues/6392

说实话,我不知道它是否适合我的问题。

非常感谢!

+1

即使您命名键0-n,您的第一项不是数组。 {}是一个对象(不用于ngfor),[]是一个数组(你在ngfor中使用的)。 –

+0

是的,这是解决方案! – JamesAnd

由于错误提示对象应该是对象的对象,根据你的JSON对象的对象应该是对象的array。你需要有适当的JSON数组,或者转换为对象数组。

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

如何将其转换为对象数组? – JamesAnd

+1

在这里检查https://stackoverflow.com/questions/39360863/javascript-converting-object-of-objects-to-array-of-objects – Sajeetharan

+0

@JamesAnd:做'this.objects = Object.values(this.objects) ;' – BeetleJuice