Angular 7 Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays

13,588

Solution 1

So, use the below as you can see that the response is not an array but one of its fields is an array. So, you have to iterate on the array field.

*ngFor="let use of userService.users?.docs"

Solution 2

You should store your users in a local array of User in the component, and user the *ngFor on the users.docs

component.ts:

users: User[];

refreshUserList(){
    this.userService.getAllUsers().subscribe(res => {
      res !== null : this.docs = res.docs;
    })
};

component.html:

<tr *ngFor="let user of users?.docs">
  <td>{{ user.fullName }}</td>
</tr>
Share:
13,588

Related videos on Youtube

sun
Author by

sun

Updated on June 04, 2022

Comments

  • sun
    sun almost 2 years

    I'm getting error while retrieving data from the database.

    Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

    I tried all the remaining responses but I'm not getting the exact solution.

    my service.ts:

      users: User[];
      getAllUsers(){
        return this.http.get(environment.apiBaseUrl + '/users');
      }
    

    my component.ts:

      refreshUserList(){
        this.userService.getAllUsers().subscribe((res) => {
          this.userService.users = res as User[];
        })
      };
    

    my component.html:

    <tr *ngFor="let use of userService.users">
      <td>{{ use.fullName }}</td>
    </tr>
    
    • dileepkumar jami
      dileepkumar jami about 5 years
      Can you please console.log the response?
    • Vinko Vorih
      Vinko Vorih about 5 years
      so you've done something weird. your response isn't typeof User[]. Try add response type in getAllUsers() method (User[]). and in http.get add this.http.get<User[]>(environment.apiBaseUrl + '/users');
    • sun
      sun about 5 years
      {status: true, docs: Array(5)} this is my console.log of response @dileepkumarjami
    • ForestG
      ForestG about 5 years
      try *ngFor="let use of userService.users?.docs" as you reference the wrong object in the template according to the console.log.
    • sun
      sun about 5 years
      Thanks @ForestG it's working..
    • Kamil Naja
      Kamil Naja about 5 years
      Displaying data from service inside template is not a good idea, better use component method or field