2017-04-15 54 views
0

假设我在Angular 2中有一个AuthGuard,用于检查我是否登录。如果我没有登录,我会重定向到/登录。重定向逻辑位于AuthGuard中。有没有在Angular路由中替换CanNotActivate的好方法?

path: '', 
component: HomeComponent, 
canActivate: [AuthGuard] 

但是如果我已经登录,并尝试去/登录页面。如果用户已经登录并尝试访问/登录页面,那么重定向到主页的最佳方式是什么?路由器上没有canNotActivate。我应该做两个AuthGuards吗?一个叫做AuthGuardNegate的东西?

有没有很好的方法呢?

回答

1

我这样做的方式是使用AuthGuard作为需要验证的页面,并使用一个UnauthGuard作为您希望仅在未登录时显示的页面;就像你说的。 可能不是最好的方式,但该工作得很好:

import {Injectable} from '@angular/core'; 
import {CanActivate, Router} from '@angular/router'; 
import {AuthService} from '../services/auth.service'; 

@Injectable() 
export class UnauthGuard implements CanActivate { 

    constructor(private router: Router, private authService: AuthService) {} 

    canActivate() { 
     if (this.authService.isLoggedIn()) { 
      this.router.navigate(['/app']); //Path to your authenticated-only page 
     } 
     return true; 
    } 
} 

和你的路由模块:

{ 
    path: 'login', 
    component: LoginPage, 
    canActivate: [ 
     UnauthGuard 
    ] 
}, 
相关问题