【发布时间】:2019-01-28 02:13:38
【问题描述】:
我在使用从 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
}
【问题讨论】:
-
好吧,当你得到一个随机用户时,你似乎只得到一个对象(这是有道理的)你试图像数组一样迭代它。
-
@AJT_82 是的!那讲得通。当调用一个人时,它是一个对象,但多个它是一个数组。是否可以根据情况让用户动态地同时充当数组和对象?
标签: angular typescript api