【问题标题】:CanActivate: Converting Observable<Observable<boolean>> to Observable<boolean>CanActivate:将 Observable<Observable<boolean>> 转换为 Observable<boolean>
【发布时间】:2017-11-16 04:58:29
【问题描述】:

我有一个只有所有者才能访问的用户设置页面。我想使用 CanActivate 来实现限制。 CanActivate 要求输出为布尔值或布尔值的可观察值。但是,我的代码输出一个可观察的布尔值。

Type 'Observable<Observable<boolean>>' is not assignable to type 'boolean | Observable<boolean> | Promise<boolean>'.

这是我的代码

@Injectable()
export class UserGuard implements CanActivate {

  constructor(
    private route: ActivatedRoute,
    private userService: UserService
  ) { }

  canActivate() {
    const username = this.route.snapshot.paramMap.get('username');

    return this.userService.authState().map(auth => {
      return this.userService.getByUid(auth.uid).map(user => {
        return user.username === username ? true : false;
      });
    });
  }
}

【问题讨论】:

    标签: angular observable angular2-observables canactivate


    【解决方案1】:

    使用.switchMap 以展平可观察对象。在这里阅读更多内容:https://www.learnrxjs.io/operators/transformation/switchmap.html

    基本上,如果您将.switchMap 链接到源 observable 并返回内部 observable,则 将订阅 observable 并发出其值,而不是发出 observable 本身:

    return this.userService.authState().switchMap(auth => {
    

    在这种情况下,您还可以通过将 .map 链接到原始可观察流来稍微扁平化您的代码。

    return this.userService.authState().switchMap(auth =>
      this.userService.getByUid(auth.uid)
    ).map(user => user.username === username);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-11
      • 2018-12-27
      • 2020-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-30
      • 1970-01-01
      相关资源
      最近更新 更多