Answer the question
In order to leave comments, you need to log in
How to close routing to Angular 2-5 component?
the essence is this. I do Authorization. I figured out how to make AuthGuard to check token .... Everything works well. But now I need to close access to the login page... since I'm already logged in and have a token.... Example below:
export class AuthService {
constructor(public jwtHelper: JwtHelperService ) {}
public isAuthenticated(): boolean {
// true или false - не стал приводить весь код чтоб не путать, вы поймете
return true;
}
}
export class AuthGuardService implements CanActivate {
constructor(public auth: AuthService, public router: Router) {}
canActivate(): boolean {
if (!this.auth.isAuthenticated()) {
this.router.navigate(['/login']);
return false;
}
return true;
}
}
const routes: Routes = [
{
path: '',
component: AuthComponent,
children: [ {path: 'login', component: LoginComponent} ]
},
{
path: '',
component: contentComponent,
canActivate: [AuthGuard],
children: [ {path: 'map', component: MapComponent} ]
},
];
// добавил AuthGuard к login
const routes: Routes = [
{
path: '',
component: AuthComponent,
canActivate: [AuthGuard],
children: [ {path: 'login', component: LoginComponent} ]
},
{
path: '',
component: contentComponent,
canActivate: [AuthGuard],
children: [ {path: 'map', component: MapComponent} ]
},
];
//добавил в Guard условие else if
export class AuthGuardService implements CanActivate {
constructor(public auth: AuthService, public router: Router) {}
canActivate(): boolean {
if (!this.auth.isAuthenticated()) {
this.router.navigate(['/login']);
return false;
} else if (this.auth.isAuthenticated()){
this.router.navigate(['/map']);
return false;
}
return true;
}
}
Answer the question
In order to leave comments, you need to log in
Make another loginGuard, and write logic in it separately.
export class loginGuard implements CanActivate {
constructor(public auth: AuthService, public router: Router) {}
canActivate(): boolean {
if (!this.auth.isAuthenticated()) {
return true;
} else if {
this.router.navigate(['/map']);
return false;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question