angular – 在’authGuard’中的canActivate无法读取AuthServer的’可观察的当前用户’

前端之家收集整理的这篇文章主要介绍了angular – 在’authGuard’中的canActivate无法读取AuthServer的’可观察的当前用户’前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用angular2 rc.3和@ angular / router“:”3.0.0-alpha.7

我的auth.server

export class AuthService {
  isLogged:boolean;
  constructor(private principal:PrincipalService){
  this.authenticated();
}
  authenticated() {
    this.principal.currentUser().subscribe(
      e=> {
        if (!!e && e.authenticated) {
          this.isLogged = true;
        }
        this.isLogged = false;
      },error=> {
      this.isLogged = false;
    }
    )
  }

AuthGuard:

constructor(private auth:AuthService )  {}
canActivate(next: ActivatedRouteSnapshot,state: RouterStateSnapshot): boolean{ 
   // here the **auth.isLogged** is undefined !! why?**
    if(this.auth.isLogged){
      return true;
    }
     else {
      window.location.href='/login';
      return false;
    }

我设置了路由器

{
      path: 'property',component: PropertyHomeComponent,canActivate: [AuthGuard]
    }

当我打开’/ property’页面时,AuthGuard无法读取“this.auth.isLogged”,也没有重定向到’/ login’页面,

怎么解决

解决方法

我找到了革命. (感谢@Michael的提示)

AuthGuard

return this.principal.currentUser().map(e=> {
      if (e) {
        return true;
      }
    }).catch(()=> {
      window.location.href = ConstantService.loginUrl;
      return Observable.of(false)
    })
  }

猜你在找的Angularjs相关文章