首页 > 解决方案 > 如何获取用户 ID 并返回他的帖子及其评论 n angular 6

问题描述

如何从他们的用户 ID中获取所有用户并对其进行迭代,当我单击特定用户时,我会得到他的所有帖子和评论?

您可以从此 API 获取帖子:https ://jsonplaceholder.typicode.com/posts

以及他们对此 API 的评论:https ://jsonplaceholder.typicode.com/comments

这是我的一个测试stackblitz项目: https ://stackblitz.com/edit/angular-g5fqzi

getUserPosts(userId: number) {
  this.http.get(`${this._postsURL}`)

  //.pipe(filter(data => userId === userId))
  //this.http.get(`${this._postsURL}/${userId}`)
    .subscribe(data => {
     //this.UserPosts  = data;
      let resources = data[userId];
      this.UserPosts = resources;
      console.log(this.UserPosts);
    })

标签: jsonangulartypescriptrxjsangular6

解决方案


Qusay,如果我理解正确,您正在尝试仅获取特定 userId 的帖子。

如果您正在发出新的 HTTP 请求,您可以在请求中传递 userId,只获取您想要的帖子,如下所示:

this.http.get(`${this._postsURL}?userId=${userId}`)
  .subscribe(data => {
    // do stuff
  });

但是,如果您已经在内存中拥有所有帖子(来自先前的请求)并且只想选择特定 userId 的帖子,您可以这样做:

const userPosts = this._postsArray.filter(post => post.userId == userId);

或者如果总是只有一个结果,您可以使用该方法find而不是filter,请记住 find 返回值,而 filter 返回一个带有该值的新数组。

const userPosts = this._postsArray.find(post => post.userId == userId);

我希望这有帮助。


推荐阅读