Error trying to diff '[object Object]'. Only arrays and iterables are allowed. (Ionic 3)

点点圈 提交于 2019-12-23 05:13:06

问题


I'm doing a project and I keep getting the error "Error trying to diff '[object Object]'. Only arrays and iterables are allowed" I looked up the error and there is two ways to do it, change the incoming data(no possible) or "transform the object in my component". I need to do the latter, but i can't find any way how to as I'm only a student. Here's some of the relevant code:

//characters.ts

     apiUrl = 'https://swapi.co/api/people';

     getUsers() {
     return new Promise(resolve => {
     this.http.get(this.apiUrl)
     .subscribe(data => {
      resolve(data);
     }, err => {
     console.log(err);
    });
   });

//home.ts

  users: any= [];

  constructor(public navCtrl: NavController, public restProvider: 
  CharactorsProvider) {
  this.getUsers();
 }


  getUsers() {
  this.restProvider.getUsers()
  .then(data => {
  this.users = data;
  console.log(this.users);
 });
 }

//home.html

 <ion-list>
 <ion-item *ngFor="let user of users">
  <p>{{charactor.results}}</p>
 </ion-item>
 </ion-list>
</ion-content>

Please any help with changing the code would be a huge help. I'm new to ionic, only a few weeks in and have a basic knowledge of it

edit: code not in boxes edit 2: api I'm using https://swapi.co/api/people/


回答1:


Well based on the JSON you posted above, it looks like you have a Object instead of array.

As the error stated above "Error trying to diff '[object Object]'. Only arrays and iterables are allowed" you need array to iterate over using ngFor.

Either change your API to send the response as array, or push the object to an array.

Also you have an issue in ngFor variable

<ion-item *ngFor="let user of users">
  <p>{{user.name}}</p> //access each user object from array
 </ion-item>

EDIT

When i looked in the response, actually you should access the results property from the response which is an array.

this.http.get('https://swapi.co/api/people/')
      .subscribe((res: Response) => {
        this.users = res.json().results; 
      }, error => {
        console.log(error);
        this.errorFromSubscribe = error;
});

HERE IS A WORKING STACKBLITZ



来源:https://stackoverflow.com/questions/50119750/error-trying-to-diff-object-object-only-arrays-and-iterables-are-allowed

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