API请求不会随机化,也不会显示



我遇到了一个从API获取随机用户的按钮的问题。当检索所有用户时,信息显示时不会出现问题,但当随机选择一个用户时,它就不起作用了。此外,它不会在每次只保留为一个用户时随机化。错误消息:ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'John Doe'. NgFor only supports binding to Iterables such as Arrays.service file:

randomNumber = Math.floor(Math.random() * 10)
random(){
return this._httpClient.get(`${this.placeholderApi}/users/${this.randomNumber}`)
}

html file:

<div *ngFor="let user of users" class="container emp-profile">
<h5>
{{user.name}}
</h5>

users.component.ts

export class UsersComponent implements OnInit {
users;
getRandomUser() {
this.clearUsers()
this._dataService.random().subscribe(
result => this.users = result
)
}
clearUsers() {
this.users = null 
}

正如我们所确定的,当检索随机用户时,您只得到一个对象,这意味着Angular将抛出一个关于*ngFor尝试迭代该对象的错误。我看到的最简单的解决方案是,当您获得一个用户时,只需将其推送到users数组。这意味着模板没有变化。

同样,在清除数组时,将其设置为空数组,否则angular会抱怨试图推送到undefined。我个人也总是喜欢通过将数组设置为空来初始化/清除数组。

因此进行以下更改:

export class UsersComponent implements OnInit {
users = [];
getRandomUser() {
this.users = [];
this._dataService.random().subscribe(
result => this.users.push(result)
// or this.users = [result] // which wouldn't throw undefined error
)
}

所以现在你的users仍然是一个数组!

最新更新