首页 > 解决方案 > 通过具有多个 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);
      });
    });
  }

标签: angularresthttp

解决方案


您需要在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)
)

这将防止每次您尝试获取收藏夹时都对服务器进行新调用。


推荐阅读