Answer the question
In order to leave comments, you need to log in
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));
});
Answer the question
In order to leave comments, you need to log in
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]) => {...})
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 questionAsk a Question
731 491 924 answers to any question