Maybe you need two different guardians. One in case the user is already logged in and the other case is not yet logged in.
Here I go like this, maybe I’ll help you:
export class AuthGuard implements CanActivate {
constructor(private router: Router){}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | boolean {
if(localStorage.getItem('token') != null){ //Se tiver token permite acessar a dash
return true;
}else{
this.router.navigate(['/login']);
return false;
}
}
}
Guard if not yet logged in:
@Injectable()
export class LoginGuard implements CanActivate {
constructor(private router: Router){}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | boolean {
if(localStorage.getItem('token') == null){ //caso o usuário ainda não tiver token(ainda não logou), permite acesso a tela de login, caso contrário é redirecionado para a home em caso de tentar acessar a rota de login já estando na home
return true;
}else{
this.router.navigate(['dash/home']);
return false;
}
}
}
Routes of my Dash:
{
path: 'dash',
component: HomeComponent,
canActivate:[AuthGuard],
children: []...
}
Login routes:
const routes: Routes = [
{
path: '',
redirectTo: 'login'
},
{path: 'login', loadChildren: 'src/app/components/entrar-app/login/login.module#LoginModule', canActivate:[LoginGuard] },
{path: 'registrar', loadChildren: 'src/app/components/entrar-app/registrar/registrar.module#RegistrarModule', canActivate:[LoginGuard] },
{path: 'recuperarsenha/:token', component: CallbackrecuperacaosenhaComponent}
];
Possible duplicate of How to make an auth Guard correctly?
– André Roggeri Campos