Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/neo4j/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何始终如一地实现可观察性?(RxJS)_Angular_Rxjs_Observable_Subscribe - Fatal编程技术网

Angular 如何始终如一地实现可观察性?(RxJS)

Angular 如何始终如一地实现可观察性?(RxJS),angular,rxjs,observable,subscribe,Angular,Rxjs,Observable,Subscribe,我遇到了一个问题: 我需要先获取评论数据(针对用户),然后获取用户数据,并将评论与用户关联起来: 结构数据: comment: id, date, userId, message -------- user: id, name 我想获取评论,并为每个获取评论添加用户名。 即,我希望评论包含用户名: comment: id, date, userId, message, userName 我阅读了rxjs的文档,但是由于各种操作符的丰富性,我不知道什么适合我 我试试看 //get comm

我遇到了一个问题: 我需要先获取评论数据(针对用户),然后获取用户数据,并将评论与用户关联起来:

结构数据:

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.userService.searchUsers({ id: ids });
您可以将其与
注释
(您已经拥有)结合使用:


一种方法可能是

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

附带问题,但是:为什么使用reduce而不是map?
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
  })
)