I am currently troubleshooting an issue with the router.navigate(['']) code that is not redirecting the user to the login component as expected. Instead of navigating to the login component, I find myself stuck on the home component. Upon adding debugger; to the code, it appears that the program enters into some kind of infinite loop.
Here is the sequence of events: When a user visits the site, they are immediately redirected to /login due to the Route Guard failing. After successfully logging in, the Route Guard passes and the user should be directed to [' '] which represents the HomeComponent. However, upon clicking logout, I expect the navigation to [' '] to fail and simply redirect back to /login. Strangely, the application remains on the HomeComponent without navigating away.
home.component.ts
logout() {
this.userService.logout();
this.router.navigate(['']);
}
user.service.ts
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
let url: string = state.url;
return this.verifyLogin(url);
}
verifyLogin(url: string): boolean {
if (this.userLoggedIn) { return true; }
this.router.navigate(['/login']);
return false;
}
logout() {
this.userLoggedIn = false;
}
app-routing.module.ts
const routes: Routes = [
{ path: '' , component: HomeComponent, canActivate: [UserService]},
{ path: 'login', component: LoginComponent },
{ path: 'register', component: RegisterComponent },
{ path: '**' , redirectTo: '' }
];