Angular 2/4:如果用户已经登录,如何限制对登录路由的访问?

时间:2017-06-16 16:11:49

标签: javascript angular

我有以下路线定义。

export const Routes = RouterModule.forChild([
    {
        path: 'login',
        component: LoginComponent
    },
    {
        path: 'protected',
        canActivate: [AuthGuardService],
        component: ProtectedComponent
    },
    {
        path: 'home',
        component: HomeComponent,
        canActivate: [AuthGuardService],
    },
]);

我已成功实施AuthGuardService,如果用户未登录,则会限制对受保护路由的访问。

我想要实现的是,如果用户已经登录并访问了登录路由,我希望它重定向到主页之类的其他路由。

1 个答案:

答案 0 :(得分:15)

如果我是你,我可能会简单地实现另一个与您的AuthGuardService完全相反的GuardService - 只允许用户f.e.本地存储中没有会话令牌。然后使用它来保护登录组件。

export const Routes = RouterModule.forChild([
    {
        path: 'login',
        canActivate: [AnonymousGuardService],
        component: LoginComponent
    },
    {
        path: 'protected',
        canActivate: [AuthGuardService],
        component: ProtectedComponent
    },
    {
        path: 'home',
        component: HomeComponent,
        canActivate: [AuthGuardService],
    },
]);