登录/登录后,应重定向到主页

时间:2020-05-08 12:43:26

标签: angular angular8

问题:

用户成功登录后,它将导航到主页。再次,如果用户尝试在URL上使用/ login,则它将导航回到登录页面。如果已经登录,则应导航到主页而不是登录页面。我该怎么做到。

这是我的路线

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
   { path: 'home', component: HomeComponent, canActivate: [AuthGuard] },
   { path: 'login', component: LoginComponent },
   { path: '**', redirectTo: '' }
 ];

授权保护服务。

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        const currentUser = this.authenticationService.currentUserValue;

        console.log("current User 2:"+currentUser);

        if (currentUser) {
            // logged in so return true
            return true;
        }

        // not logged in so redirect to login page with the return url
        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
        return false;
    }

1 个答案:

答案 0 :(得分:1)

您可以像这样保护登录页面:

守卫:

constructor(private authenticationService: AuthenticationService){}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        return !this.authenticationService.isLoggedIn();
    }

路由模块:

{ path: 'login', component: LoginComponent, canActivate: [LoginGuard] }
相关问题