0

大家好,我有一小段代码没有编译。我在我的代码中使用 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 }    
);

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

4

1 回答 1

2

据我了解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 }    
);
于 2019-07-16T10:53:29.680 回答