M
M
Mikhail2019-09-19 14:21:09
Angular
Mikhail, 2019-09-19 14:21:09

What is the best way to merge queries by condition?

Good afternoon.
The essence of the question is this:
1. A request is made to the server post = getPostByName(name)
2. The post id is searched for tags post.tags = getTagsByPostId(post.id)
3. If the post has comments, the post.comments comments are searched = post.hasComments ? getCommentsByPostId(post.id) : null
If the first two points can be done via mergeMap , then the third point is unclear how to solve.

this.postService.getPostByName(name)
.pipe(
  mergeMap( 
    post => this.postService.getTagsByPostId(post.id),
      (post, tags) => {
        post.tags = tags;
        return post;
    }
),
.subscribe( post => {
  this.posts.push(new Post(post));
});

What is the best way to add another conditional query and wait for it to complete? The problem is that all the data must come to the constructor already formed, i.e. must wait for two (or three) queries to complete before passing to the new Post(post) constructor

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Shvets, 2019-09-19
@VK_31

well something like this

this.postService.getPostByName(name).pipe(
  mergeMap(post => forkJoin([
    of(post),
    this.postService.getTagsByPostId(post.id),
    iif(() => post.hasComments(), this.getCommentsByPostId(post.id), of(null)),
  ]))
)
  .subscribe(([post, tags, comments]) => {...})

It is better to put the components into custom statements so that the code can be read

M
msdosx86, 2019-09-21
@msdosx86

this.postService.getPostByName(name)
  .pipe(
    switchMap(post => this.postService.getTagsByPostId(post.id)
      .pipe(
        tap(tags => post.tags = tags),
        mapTo(post),
        filter(() => post.hasComments),
        switchMap(() => this.postService.getCommentsByPostId(post.id)),
        tap(comments => post.comments = comments),
        mapTo(post),
      )
    ),
  )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question