Reputation: 23
I have Login/Create Account in My application. I want the user will not be able to see login/create account if user is already logged in. I am using an Authguard to protect the route:
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {debugger;
if (localStorage.getItem('UserLoggedIn')) {
// logged in so return true
this.router.navigate(['']);
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['login']);
return false;
}
In this case the page is going in infinite loop.
This is my Routes:
const appRoutes: Routes = [
{ path: '', component: HomeComponent , data: { animation: '' }},
{ path: 'login', component: UserloginComponent , data: { animation: 'login' },canActivate:[AuthGuard]},
{ path: 'create-account', component: CreateAccountComponent, data: { animation: 'create-account' } },
{ path: 'forgot-password', component: ForgotPasswordComponent, data: { animation: 'forgot-password' } },
{ path: '**', component: PageNotfoundComponent }
];
Please Help. I want it for login and create account.
Upvotes: 0
Views: 137
Reputation: 752
It is because you added this.router.navigate(['login']);
to your authguard and this authguard was attached to login
route. Each time a route was accessed it always call all the guards that was attached. So in your case if you access login, it will infinitely redirect to login. There are many ways to solve your issue. If you are intending to add the guard on the login route, just remove this.router.navigate(['login']);
to avoid infinite loop. But i suggest to add the guard only to those routes you want to protect being accessed at if the user is not logged in.
Upvotes: 1
Reputation: 5267
Try this:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {debugger;
let redirect: boolean = false;
if (localStorage.getItem('UserLoggedIn')) {
// logged in so return true
this.router.navigate(['']);
redirect = true;
} else {
// not logged in so redirect to login page with the return url
this.router.navigate(['login']);
redirect = false;
}
return redirect;
}
Upvotes: 0