Angular router.navigate w/ route guard not working when already on Component
angular, angular-components, angular-routing, javascript, typescript
Solution
Why it should navigate it is already in [' '] and you ask again go to [' ']? You can call 'this.router.navigate(['/login'])' in logout.
logout() {
this.userLoggedIn = false;
this.router.navigate(['/login']);
}
Problem
I am trying to figure out why the router.navigate(['']) code below does not take the user to the login component. I just stay on the home component. When I added debugger; to the code it seems like it goes into some sort of endless loop. Here is the process: User comes to site and instantly gets redirected to /login since the Route Guard fails. If they login, Route Guard passes and they go to [' '] which is the HomeComponent. Then when they click logout I figure the navigate to [' '] should fail and simply go to /login. For some reason it stays on the HomeComponent and never navigates. 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: '' } ]; ```