urosbelov
urosbelov

Reputation: 349

Angular loop through posts with multiple id

I want to loop through GET request of posts and get favorite posts from favorite id array

I have tried code bellow but i don't know is this the best way

data.service.ts

getPosts(): Observable<Post[]> {
    return this.http.get<Post[]>(this.postsUrl);
  }

I want to get all posts from array of favorite posts by they ID Component

 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);
      });
    });
  }

Upvotes: 1

Views: 861

Answers (1)

Jesse
Jesse

Reputation: 2597

You'll want to use the map operator here to map your posts ahead of your subscribe:

this.serverService.getPosts().pipe(
      map(posts => posts.filter(post => this.favoriteIds.includes(post.id)))
).subscribe(data => this.posts = data)

Another thing you'll want to do is get rid of your getPosts() method and just use a local Observable assignment with the shareReplay(1) operator:

getPosts$ = this.http.get<Post[]>(this.postsUrl).pipe(
      shareReplay(1)
)

This will prevent a new call from being made to the server every time you try to get favorites.

Upvotes: 2

Related Questions