json - 如何获取用户 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);
})
解决方案
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);
我希望这有帮助。
推荐阅读
- java - 并行流() java 1.8 与 11
- azure - azure datalake gen2 databricks ACL 权限
- c++ - 如何在没有taskkill的情况下重新启动资源管理器
- flutter - Flutter:无法将 ListView 添加到示例应用程序
- swiftui - SwiftUI 列表未显示任何项目
- visual-studio - 'SMTP 服务器需要安全连接或客户端未通过身份验证。服务器响应为:5.7.0 Authentication Required
- javascript - 如何在html5和js中下载部分视频
- javascript - 替代“onScroll”来隐藏导航栏?
- asp.net - 如何让 IIS 尊重相对路径?
- mongodb - MongoDB聚合检查数组是否包含值