首页 > 解决方案 > 如何从代码中的 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 }    
);

知道如何重写代码片段以使其正常工作吗?太感谢了

标签: typescriptrxjs

解决方案


据我了解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 }    
);

推荐阅读