typescript - 如何从代码中的 Rxjs 可观察值中获取价值?
问题描述
大家好,我有一小段代码没有编译。我在我的代码中使用 angular 5 、 rxjs 和 typescript 。
错误是无法分配 this.account = value 。它说 value 是 Observable 并且不能分配给 this.account 这是一个 Account 对象。
this.authenticationService.currentUser$.pipe(
map( user => user.account.id),
map( id => this.accountService.get(id) )
).subscribe(
value => { this.account = value }
);
知道如何重写代码片段以使其正常工作吗?太感谢了
解决方案
据我了解this.accountService.get(id)
返回 Observable,在这种情况下您需要使用switchMap()
而不是map()
运算符,否则您将在 subscribe 中获得 Observable 而不是您感兴趣的值。
您的示例将变为:
this.authenticationService.currentUser$.pipe(
map(user => user.account.id),
switchMap(id => this.accountService.get(id)),
).subscribe(
value => { this.account = value }
);
推荐阅读
- java - 我无法从 string.xml 中存在的整数数组中取出元素
- android - 在 webview/webkit 中以编程方式按下按钮
- perl - Perltex:如何输出到乳胶文件?
- amazon-web-services - 在无需公开 s3 存储桶的情况下,最接近在 S3 中执行符号链接功能的方法是什么?
- python - 使用 2 个坐标选择数组中的项目并填充它
- matlab - 有没有办法在 MATLAB/Psychtoolbox 中覆盖下划线?
- python - 数组 python || 时间.strftime
- jenkins - 如何将 Jenkins 凭据传递给 gradle?
- neo4j - 使用 apoc load jdbc 进行嵌套 apoc 迭代返回“无法以 CALL 结束”消息
- java - 在java中同步一个没有在类中使用的Object类对象