【问题标题】:API request does not randomize and does not displayAPI请求不随机化,不显示
【发布时间】: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


【解决方案1】:

正如我们所建立的,当检索一个随机用户时,您只会得到一个对象,这意味着 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 仍然是一个数组!

【讨论】:

  • 成功了!非常感谢您花时间解决这个问题。非常感谢!
  • 没问题,很高兴能帮上忙! :)
猜你喜欢
  • 2015-05-15
  • 2017-11-29
  • 1970-01-01
  • 1970-01-01
  • 2021-02-26
  • 1970-01-01
  • 2012-01-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多