【问题标题】:find object of particular id in json in html tamplate在 html 模板中的 json 中查找特定 id 的对象
【发布时间】:2018-11-12 13:28:31
【问题描述】:

我正在编写呈现帖子的页面。

在我的控制器中,我有:

export class PostsComponent implements OnInit {

  posts$: Object;
  users$: Object;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.getPosts().subscribe(
      data => this.posts$ = data
    )
    this.data.getUsers().subscribe(
      data => this.users$ = data
    )
  }

}

在模板中,我遍历帖子以呈现它们:

<h1>Posts</h1>

<ul>
  <li *ngFor='let post of posts$'>
    <h3>{{ post.title }}</h3>
    <h5>created by:</h5>
    <p>{{ post.body }}</p>
  </li>
</ul>

在“创建者:”之后,我想添加{{user$.username}},其中user$ 应该是来自users$ 的post.userId 的用户(已经在控制器中初始化)。方法getUsersgetPosts 工作正常并从https://jsonplaceholder.typicode.com 获取数据。我还编写了getUser(id) 方法,我想我可以使用那个方法。那么它应该在控制器中:

this.data.getUser(id).subscribe(
  data => this.users$ = data
)

但是当我遍历模板中的帖子时,我不知道从哪里获得id。你能帮我解决这个问题吗?

【问题讨论】:

  • &lt;li *ngFor='let post of posts$; let i = index'&gt;你的意思是?

标签: html json angular


【解决方案1】:

您可以在您的组件中创建一个函数getUser(id) 并让它返回用户。

在你的 html 中

{{ getUser(post.userId) }}

或者

this.data.getPosts().subscribe(
  data => { 
   for(let i = 0; i < data.length; i++) {
     data[i].username = this.getUser(data[i].userId);
   }
   this.posts$ = data;
})

【讨论】:

  • 我明白了,谢谢!但是由于某些原因,在我的组件中我不能使用 this.posts$.length 或 this.posts$.forEach。它说没有为 Object 定义 length 和 forEach - 我理解。但我不明白为什么我可以在 html 中使用 *ngFor='let post of posts$' 。以及如何在组件中处理。
  • 我更改了代码长度,应该在data 上可用,之后您可以将其设置为this.post$ = data
猜你喜欢
  • 1970-01-01
  • 2018-03-24
  • 2013-06-22
  • 1970-01-01
  • 2017-11-27
  • 2017-07-03
  • 1970-01-01
  • 1970-01-01
  • 2011-10-16
相关资源
最近更新 更多