2

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>
veben
  • 19,637
  • 14
  • 60
  • 80
sun
  • 1,832
  • 4
  • 19
  • 31

3 Answers3

4

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"
dileepkumar jami
  • 2,185
  • 12
  • 15
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>
veben
  • 19,637
  • 14
  • 60
  • 80
0

In other way, you can check the data is ready to serve in html file by the following way.

<div *ngIf="userService.users?.length > 0">
   <tr *ngFor="let use of userService.users">
       <td>{{ use.fullName }}</td>
    </tr>
</div>
Ahmad Sharif
  • 4,141
  • 5
  • 37
  • 49