angular - 通过具有多个 id 的帖子的角度循环
问题描述
我想遍历帖子的 GET 请求并从最喜欢的 id 数组中获取最喜欢的帖子
我试过下面的代码,但我不知道这是最好的方法
数据服务.ts
getPosts(): Observable<Post[]> {
return this.http.get<Post[]>(this.postsUrl);
}
我想通过他们的 ID 组件从最喜欢的帖子数组中获取所有帖子
getFavorites(): void {
this.serverService.getPosts().subscribe(posts => {
this.favoriteIds.forEach(element => {
let data = posts.filter(post => post.id === element);
this.posts = data;
console.log(this.posts);
});
});
}
解决方案
您需要在map
此处使用运算符在订阅之前映射您的帖子:
this.serverService.getPosts().pipe(
map(posts => posts.filter(post => this.favoriteIds.includes(post.id)))
).subscribe(data => this.posts = data)
您要做的另一件事是摆脱您的 getPosts() 方法,只需使用带有 shareReplay(1) 运算符的本地 Observable 分配:
getPosts$ = this.http.get<Post[]>(this.postsUrl).pipe(
shareReplay(1)
)
这将防止每次您尝试获取收藏夹时都对服务器进行新调用。
推荐阅读
- python - Discord.py 将未知频道消息保存到 txt 文件中
- microsoft-graph-api - Beta Graph API eDiscovery Review Set Apply Tag 似乎只标记了 Group/Section 标签而不是子标签
- raspberry-pi - 如何在 QEMU 中运行的树莓派中扩展文件系统?
- python - python 关于在 MRI 切片数据集上训练深度神经网络
- scala - spark 3.2.0 不同的dataframe createOrReplaceTempView 同名TempView
- python - 在类中的函数调用中将“self”作为参数传递(Python)
- ruby-on-rails - AWS Elastic Beanstalk 跳过 db:migrate,获得 RAILS_SKIP_MIGRATIONS 的错误值
- javascript - javascript [1,2,3,4] 变为 12, 23, 34
- spring-boot - Spring Tomcat 在哪里/如何修改 TOMCAT_HOME/conf
- html - Wget 如何在 url 上排除/包含特定链接