【问题标题】:*ngFor="let hero of usersList" Error trying to diff. Only arrays and iterables are allowed*ngFor="let hero of usersList" 尝试区分时出错。只允许使用数组和可迭代对象
【发布时间】:2021-06-11 10:46:20
【问题描述】:

我正在努力理解为什么我无法在使用 ngFor 的所有用户和表格中的组件的 html 中看到。在 usersList: User[] 中保留的接缝是 User 类型的数组列表的响应,如下图所示 PtrSCr of the Web page and the console error 但最后它说 错误:尝试比较时出错 '[{"id":101,"userName":"tcorneanu","password":"password","email":"tcorneanu@gmail.com"} ,{"id":104,"userName":"user3","password":"pwd3","email":"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;
}

【问题讨论】:

  • 这能回答你的问题吗? Angular4 Error trying to diff '[object Object]'
  • 如果你这样做console.log(data)会得到什么?
  • 你检查了typeof data 吗?也许它的 Response 对象,您需要使用 data.json() 获取用户数组
  • @Kenny 检查他的图片网址。他正在获取用户数组的纯字符串数据
  • 恐怕您的数据类型可能是string

标签: html angular typescript


【解决方案1】:

我将字符串转换为 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]

表格将显示表格Web Page and console in the end

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-14
    • 2020-08-15
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多