[英]how to consistently do subscribe Observable? (RxJS)
我遇到了一個問題:我需要先獲取評論的數據(針對用戶),然后獲取用戶的數據並將評論和用戶關聯起來:
結構數據:
comment:
id,
date,
userId,
message
--------
user:
id,
name
我想獲得評論並為每條評論添加用戶名。 即我想讓評論包含用戶名:
comment:
id,
date,
userId,
message,
userName
我閱讀了 rxjs 的文檔,但是由於各種運算符的豐富性,我不知道什么適合我。
我試試
//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) });
這是可行的,但我只是得到列表用戶,我不知道如何關聯來自getMovieComments()和來自searchUsers()的數據,然后獲得所需的結果。
對不起,如果那是顯而易見的事情。 我是 RxJS 的初學者
一種方法可能是以下
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
})
)
在這一行
return this.userService.searchUsers({ id: ids });
您可以將其與comments
(您已經擁有)結合起來:
return forkJoin(of(comments), this.userService.searchUsers({ id: ids }));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.