Typescript 如何从代码中可以观察到的Rxjs中获取值?

Typescript 如何从代码中可以观察到的Rxjs中获取值?,typescript,rxjs,Typescript,Rxjs,大家好,我有一小段代码,它不是编译的。我在代码中使用angular 5、rxjs和typescript 错误无法分配此。帐户=值。它表示值是可观察的,不能分配给帐户对象this.account this.authenticationService.currentUser$.pipe( map( user => user.account.id), map( id => this.accountService.get(id) ) ).subscribe( value =&

大家好,我有一小段代码,它不是编译的。我在代码中使用angular 5、rxjs和typescript

错误无法分配此。帐户=值。它表示值是可观察的,不能分配给帐户对象this.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 }    
);

据我所知,
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 }    
);

您对authenticationService.currentUser$的订阅将返回一个可观察值,而不是一个值,因为您的第二个
map()
返回
this.accountService.get(id)
。您对authenticationService.currentUser$的订阅将返回一个可观察值,而不是一个值,因为您的第二个
map())
返回
this.accountService.get(id)
。感谢您,它与开关映射一起工作。想象一下,如果我们使用mapYep,代码会是什么样子,您也可以使用其他平面图,如
concatMap
mergeMap
exhaustMap
非常感谢。对于像我们这样的新手来说非常有用的提示谢谢你它可以与开关地图一起工作。想象一下,如果我们使用mapYep,代码会是什么样子,您也可以使用其他平面图,如
concatMap
mergeMap
exhaustMap
非常感谢。对于像我们这样的新手来说非常有用的提示