2017-02-08 8 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

가드에서 리디렉션 할 수 있습니다. –

+0

탐색 한 후 왜 false가 반환됩니까? – vangoo