【问题标题】:Displaying data with ngFor in Angular properly在 Angular 中使用 ngFor 正确显示数据
【发布时间】:2019-11-19 23:45:04
【问题描述】:

我正在尝试显示从我的端点接收到的一些数据。将其打印到控制台日志可以正常工作,但我无法在 HTML 页面上显示它,即页面为空白。我试过了

<ul>
        <li *ngFor="let animal of animals | async">
                {{ animal }} 
        </li>
</ul>

这就是我设置组件的方式:

export class PageComponent implements OnInit {

  animals : Animals [];

  constructor(private store: Store) { }

  ngOnInit() {
    this.store.dispatch(fetchUsers).subscribe(animals => {
      this.animals  = animals ;
      console.log(this.animals );
    });
  }

}

在控制台中,我正在获取从端点接收的 JSON:

animals :
 animals : Array(1)
  0: {id: "1562", animalType: "dog"}

我希望它返回动物对象,但稍后我将让它打印animalType

【问题讨论】:

  • 在 HTML 中输入 {{ animal | json }}{{ animal.animalType }}
  • 还是空白:/
  • 看起来有一个额外的animals 顶级属性。请使用您的 API 调用结果的 JSON 表示来编辑您的问题。
  • 使用&lt;li *ngFor="let animal of animals"&gt;

标签: html angular ngxs


【解决方案1】:

您不需要 async 运算符,因为您没有为属性animals 使用promise 或observable,所以您只需要对它的引用。当您的阵列尚未初始化时,您还需要添加某种保护。我为此使用了 ngIf:

<ul *ngIf="animals">
        <li *ngFor="let animal of animals">
                {{ animal.animalType }} 
        </li>
</ul>

https://angular.io/api/common/AsyncPipe

然后在你的component.ts中

  ngOnInit() {
    this.store.dispatch(fetchUsers).subscribe(animals => {
      this.animals  = animals.animals ; // looks like you need to work on this
      console.log(this.animals );
    });
  }

【讨论】:

  • 是的,有一个顶级
【解决方案2】:

animals 不是可观察的,为什么要使用异步? 真的:

<ul>
        <li *ngFor="let animal of animals">
                {{ animal }} 
        </li>
</ul>

【讨论】:

    猜你喜欢
    • 2021-07-12
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-07
    相关资源
    最近更新 更多