【问题标题】:Angular 7 Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as ArraysAngular 7 找不到“object”类型的不同支持对象“[object Object]”。 NgFor 仅支持绑定到 Iterables,例如 Arrays
【发布时间】:2019-07-13 00:16:20
【问题描述】:

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

找不到“object”类型的不同支持对象“[object Object]”。 NgFor 只支持绑定到 Arrays 等 Iterables。

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

我的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>

【问题讨论】:

  • 能否请您 console.log 回复?
  • 所以你做了一些奇怪的事情。您的回复不是用户 [] 类型。尝试在 getAllUsers() 方法 (User[]) 中添加响应类型。并在 http.get 添加 this.http.get(environment.apiBaseUrl + '/users');
  • {status: true, docs: Array(5)} 这是我的 console.log 响应 @dileepkumarjami
  • 尝试*ngFor="let use of userService.users?.docs",因为您根据 console.log 在模板中引用了错误的对象。
  • 感谢@ForestG 它正在工作..

标签: javascript angular typescript angular7 angular-template


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    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>
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-04
        • 2020-10-17
        • 2017-10-15
        • 2018-07-19
        • 2017-02-10
        • 2020-03-28
        • 2018-04-07
        相关资源
        最近更新 更多