0
votes

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 are 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
What does console.log(this.users) output? - Ben West
what do you see when you put console.log(JSON.stringify(this.users)); - Sajeetharan
@BenWest The Console.log outputs the array {name: "Luke Skywalker", height: "172", mass: "77", hair_color: "blond", skin_color: "fair", …} - Jack Caltagirone
@Sajeetharan puts out the array {"name":"Luke Skywalker","height":"172","mass":"77","hair_color":"blond","skin_color":"fair","eye_color":"blue","birth_year":"19BBY","gender":"male","homeworld":"swapi.co/api/planets/1", } etc, will post the api in post - Jack Caltagirone
You need an iterable (array) from your server responses. Basically you need to grab "results" array in the response. - Sergey Rudenko

1 Answers

1
votes

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