简体   繁体   中英

Angular 2/4: How to restrict access to Login Route if user is already logged in?

I have the following route definition.

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

I have successfully implement AuthGuardService which restrict access to a protected route if user is not logged in.

What I am trying to achieve is, if user is already logged in and accessed the Login Route, I want it to redirect to another route like homepage.

Were I you, I would probably simply implement another GuardService that would work in exactly opposite way to your AuthGuardService - only allow user if fe there is no session token in local storage. And then use it to secure login component.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM