【问题标题】:Angular | NgFor to display the array contents角 | NgFor 显示数组内容
【发布时间】:2021-07-31 00:21:31
【问题描述】:

我是 Angular 的新手,并试图获取 postdata 中的值,但是当我尝试迭代它时,它只给了我第一个值。 附上我的代码:

 posts;

 constructor(private getpostservice:GetpostsService) { }

 ngOnInit(): void {
  this.getpostservice.getposts().then(data=>{
  this.posts = [data];

  console.log("Inside home",this.posts);
 })
}

这是我的 html 逻辑:

<tr *ngFor="let p of posts;index as i">


        <td>
          {{p.postdata[i].title}}
        </td>

      </tr>

.

有人可以帮我提取标题和正文吗?

【问题讨论】:

  • 尝试改变让 p of posts.postdata 然后 {{p.title}}
  • 为什么将数据存储为数组this.posts = [data];?如果您的请求响应数据是一个数组,那么您将有一个数组数组 - 坏主意。如果它只是一个对象,那么你就不需要循环来迭代它。
  • @Fussel 先生,您能否提供另一种以角度呈现数据的方法?这将非常有帮助。
  • 可能你正在寻找嵌套的 *NgFor 在这种情况下类似于这里 - stackblitz.com/edit/…

标签: angular express


【解决方案1】:

我认为您根据控制台数据尝试实现的是:

 constructor(private getpostservice:GetpostsService) { }

 ngOnInit(): void {
  this.getpostservice.getposts().then(data => {
    this.posts = data.postdata;
    console.log("Inside home",this.posts);
 });

<ng-container *ngIf="posts">
  <tr *ngFor="let p of posts">
    <td>
      {{p.title}}
    </td>
  </tr>
</ng-container>

也许你也应该考虑使用Observables 而不是Promises,这有点你必须习惯,但它更强大且更易于使用。

【讨论】:

  • 是的,关于使用 Observable 代替 Promise 的一些意见,或者另一种选择是使用异步管道
猜你喜欢
  • 1970-01-01
  • 2019-11-11
  • 2018-08-13
  • 2021-04-28
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 2021-01-04
  • 1970-01-01
相关资源
最近更新 更多