Reputation: 201
I ran into a problem: I need to get the data of comments (for users) first, secondly get data of users and correlate comments and users:
Structure data:
comment:
id,
date,
userId,
message
--------
user:
id,
name
I want to get comments and add user-name for every getting comment. I.e. I want to have comment contain user-name:
comment:
id,
date,
userId,
message,
userName
I read the documentation for rxjs, but because of the abundance of various operators I do not know what suits me.
I try it
//get comments
return this.getMovieComments(movieId).pipe(
//form array ids users by comments
mergeMap(comments => {
const ids = comments.map(c => c.userId);
//get users
return this.userService.searchUsers({ id: ids });
})
).subscribe((users) => { console.log(users) });
It is works, but I just get list users, I do not know how me correlate data from getMovieComments() and from searchUsers() then get desired result.
Sorry if that obvious things. I am beginner of RxJS
Upvotes: 0
Views: 168
Reputation: 17762
One way could be the following
return this.getMovieComments(movieId).pipe(
concatMap(comments => {
const ids = comments.map(comment => comment.id);
return this.userService.searchUsers({ id: ids }).pipe(
// via this map operation we return both the comments and the users to the next operator in the pipe
map(users => ({users, comments})
)
}),
map(({users, comments}) => {
// here users and comments are 2 arrays and so it is possible to assign the user name to the comment - the exact logic may depend on how the arrays are sorted
})
)
Upvotes: 1
Reputation: 14679
In this line
return this.userService.searchUsers({ id: ids });
you can combine it with comments
(which you already have):
return forkJoin(of(comments), this.userService.searchUsers({ id: ids }));
Upvotes: 0