我想从 API 检索用户列表。我有几个错误,例如
Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Array
或
Cannot read property 'id' of undefined” when parsing an array declared in a factory
现在我解决了这些错误,但现在的问题是,错误消失了,但我在 View 中看不到任何数据。页面只是空的。我真的不知道我可以进一步尝试什么。奇怪的是,我可以在 get (users) 中记录我的数据,并且还在我的网络选项卡中看到 200 成功,但我无法让它在我的 View 中工作。
这是我的服务:
getList(): Observable<any> {
return this.http.get<{results: any[]}>(`${this.url}/users`)
.pipe(
retry(2),
// catchError(this.handleError)
);
}
页面.ts
userList: any[] = [];
...
ngOnInit() {
this.getAllUsers(); // get the users wenn view intializes
}
getAllUsers() {
// get saved list of users
this.userService.getList().subscribe(response => {
console.log(response);
this.userList = response.results;
});
}
页面.html
<ion-list>
<ion-item lines="none" *ngFor="let user of userList.results">
<ion-avatar>
<ion-img src="assets/friends1.jpeg"> </ion-img>
</ion-avatar>
<h2 class="title">{{user.username}}</h2>
</ion-item>
</ion-list>
我的回复日志是:
results: (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
最佳答案
您已经将结果分配给 userList,因此它已经是一个数组并且不会有 results 属性。将 userList.results 更改为 ngFor 中的 userList
*ngFor="let user of userList"
最好使用异步管道而不是订阅,将您的组件更改为
userList$ = this.userService.getList().pipe(map(response => response.results));
并在模板中使用异步管道
*ngFor="let user of (userList$ | async)"
关于javascript - 请求 API 时 View 中看不到任何数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58684780/