首页 > 解决方案 > *ngFor="let hero of usersList" 尝试区分时出错。只允许使用数组和可迭代对象

问题描述

我正在努力理解为什么我无法在使用 ngFor 所有用户和表格中的组件的 html 中看到。接缝保留在 usersList: User[] 响应是 User 类型的数组列表,如 网页的下一张图像 PtrSCr 和控制台错误,但最后它说 Error: Error trying to diff '[{ "id":101,"userName":"tcorneanu","password":"password","email":"tcorneanu@gmail.com"},{"id":104,"userName":"user3", “密码”:“pwd3”,“电子邮件”:“user3@gmail.com”}]'。只允许数组和可迭代的 HTML

<h2>User list</h2>
{{usersList}}
<table class="table table-striped">
 <thead>
     <tr>
        <th>Id</th>
        <th>index</th>
     </tr>
 </thead>
 <tbody>
    <tr *ngFor="let hero of usersList; let i = index">
        <td>{{hero.id}}</td>
        <td>{{i}}</td>
    </tr>
</tbody>
</table>

TS

usersList: User[] = [];  

 private getUsersList(token:any):void{
    this.userService.getUsersList(token).subscribe(data => {
      console.log("data is: "+data),
      this.usersList = data
    }, (error) => {
      console.log(error);
    });
  }

用户服务

getUsersList(token:any): Observable<User[]>{
    let tokenStr = 'Bearer '+token;
    const headers = new HttpHeaders().set("Authorization",tokenStr);
    return this.httpClient.get<User[]>(`${this.url}/users`,{headers, responseType: 'text' as 'json'});
  }

用户

export interface  User {
    id: number;
    userName: string;
    password: string;
    email: string;
}

标签: htmlangulartypescript

解决方案


我将字符串转换为 User[] 数组

 private getUsersList(token:any):void{
    this.userService.getUsersList(token).subscribe(data => {
      console.log("data is: " +data+ typeof data),
      console.log("usersList type is: " +typeof this.usersList),
      this.string = data.toString(),
      console.log("string is of type "+typeof this.string+", value is "+this.string)
      this.array = JSON.parse(this.string);
    }, (error) => {
      console.log(error);
    });
  }

现在如果我去 HTML {{array}} 我会看到 -> [object Object],[object Object],[object Object],[object Object]

表格最后会显示表格网页和控制台

<table class="table table-striped">
 <thead>
     <tr>
        <th>Id</th>
        <th>index</th>
     </tr>
 </thead>
 <tbody>
    <tr *ngFor="let hero of array">
        <td>{{hero.userName}}</td>
        <td>{{hero.email}}</td>
    </tr>
</tbody>
</table>

推荐阅读