我使用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) }) }