2017-02-08 77 views
1

如果用戶沒有登錄,想要去一些安全的根,例如「/ items」authguard返回false並且不導航「/ login」。Angular2 Authguard登錄路徑

export const APP_ROUTES: Routes = [ 
    {path: '', component: PublicComponent, children: PUBLIC_ROUTES}, 
    { 
    path: '', 
    component: SecureComponent, 
    resolve: {user: UserResolver}, 
    canActivate: [AuthGuard], 
    children: SECURE_ROUTES 
    }, 
    {path: '', redirectTo: '/login', pathMatch: 'full'} 
]; 

AuthGuard代碼:

@Injectable() 
export class AuthGuard implements CanActivate { 
    constructor(private userService: UserService) {} 

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){ 
    let url: string = state.url; 
    return this.checkLogin(url); 
    } 

    checkLogin(url: string): Observable<boolean> { 
    this.userService.redirectUrl = url; 
    return this.userService.getPrincipal() 
     .map(user => { 
     if(user) 
      return true; 

     return false; 
     }); 
    } 
} 
+0

問題是什麼在這裏:)? –

+0

如果用戶沒有登錄,那麼我想導航登錄頁面? :) – vangoo

+0

@vangoo您是否嘗試過我的代碼? –

回答

1

進樣Router和重定向如果用戶沒有登錄在如下登錄頁面:

@Injectable() 
export class AuthGuard implements CanActivate { 

    constructor(private userService: UserService, private router: Router) {} 

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean{ 
    let url: string = state.url; 
    return this.checkLogin(url); 
    } 

    checkLogin(url: string): Observable<boolean> { 
    this.userService.redirectUrl = url; 
    return this.userService.getPrincipal() 
     .map(user => { 
     if(user) 
      return true; 

     this.router.navigate(['login']); 
     return false; 
     }); 
    } 
} 
+0

可以authguard會做導航嗎?是最好的方法? – vangoo

+0

Ofc您可以從Guard重定向。 –

+0

導航後爲什麼會返回false? – vangoo