html - *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;
}
解决方案
我将字符串转换为 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>
推荐阅读
- realm - javascript ream.close() not closing, stopped
- string - Why does open with :w and :append still overwrite the file?
- assembly - ASSUME directive using masm
- html - 悬停时无法更改css中的背景图像
- android - Using AsyncTask with Runnable vs Creating AsyncTask Class
- angularjs - Push notifications in Android 8 using IONIC v1
- google-sheets - 如何在 Google 表格中设置双向或三向交易?
- xamarin.ios - 如何在 MDHTMLLABEL 链接中应用可访问性?
- swift - 如何将 viewModel 类注入 WKInterfaceController?
- regex - 如何设置单元格中的最大字符数并在 Google 表格中达到最大字符数时自动跳过 2 行?