繁体   English   中英

Angular 7 找不到类型为“object”的不同支持对象“[object Object]”。 NgFor 只支持绑定到 Iterables,比如 Arrays

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

从数据库中检索数据时出错。

找不到类型为“object”的不同支持对象“[object Object]”。 NgFor 仅支持绑定到可迭代对象,例如数组。

我尝试了所有剩余的响应,但没有得到确切的解决方案。

我的service.ts

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

我的component.ts

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

我的component.html

<tr *ngFor="let use of userService.users">
  <td>{{ use.fullName }}</td>
</tr>

因此,使用下面的内容,您可以看到响应不是数组,而是其中一个字段是数组。 因此,您必须迭代数组字段。

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

您应该将用户存储在组件中的本地User数组中,并在*ngFor上使用*ngFor users.docs

组件.ts

users: User[];

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

组件.html

<tr *ngFor="let user of users?.docs">
  <td>{{ user.fullName }}</td>
</tr>

或者,您可以通过以下方式检查数据是否已准备好在 html 文件中提供。

<div *ngIf="userService.users?.length > 0">
   <tr *ngFor="let use of userService.users">
       <td>{{ use.fullName }}</td>
    </tr>
</div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM