如何在Angular 2 Guards的canActivate()中使用可观察对象 [英] How to use an observable in angular 2 guards' canActivate()

查看:37
本文介绍了如何在Angular 2 Guards的canActivate()中使用可观察对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经为我的angular2 rc5应用程序创建了身份验证保护.

I have created an authentication guard for my angular2 rc5 application.

我也在使用redux存储.在该商店中,我保留用户的身份验证状态.

I am also using a redux store. In that store I keep the user's authentication state.

我了解到,守卫可以返回可观察到的承诺( https://angular.io/docs/ts/latest/guide/router.html#!#guards )

I read that the guard can return an observable or promise (https://angular.io/docs/ts/latest/guide/router.html#!#guards)

我似乎无法找到一种方法来让警卫队等到更新,并且只有此后更新后才能返回警卫队,因为默认值的商店永远都是假的.

I can't seem to find a way for the guard to wait until the store/observable is updated and only after that update return the guard because the default value of the store will always be false.

第一次尝试:

@Injectable()
export class AuthGuard implements CanActivate {

  @select(['user', 'authenticated']) authenticated$: Observable<boolean>;

  constructor() {}

  canActivate(): Promise<boolean> {

    return new Promise((resolve, reject) => {

      // updated after a while ->
      this.authenticated$.subscribe((auth) => {

        // will only reach here after the first update of the store
        if (auth) { resolve(true); }

        // it will always reject because the default value
        // is always false and it takes time to update the store
        reject(false);

      });

    });

  }

}

第二次尝试:

@Injectable()
export class AuthGuard implements CanActivate {

  @select(['user', 'authenticated']) authenticated$: Observable<boolean>;

  constructor() {}

  canActivate(): Promise<boolean> {

    return new Promise((resolve, reject) => {

      // tried to convert it for single read since canActivate is called every time. So I actually don't want to subscribe here. 
      let auth = this.authenticated$.toPromise(); 

      auth.then((authenticated) => {

        if (authenticated) { resolve(true); }

        reject(false);

      });

      auth.catch((err) => {
        console.log(err);
      });

  }

}

推荐答案

订阅不会返回Observable. 但是,您可以像这样使用地图运算符:

Subscribe doesn't return an Observable. However, you can use the map operator like that:

this.authenticated$.map(
    authenticated => {
        if(authenticated) {
            return true;
        } 
    return false;
    }
 ).first() // or .take(1) to complete on the first event emit

这篇关于如何在Angular 2 Guards的canActivate()中使用可观察对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆