简体   繁体   中英

Angular router.navigate w/ route guard not working when already on Component

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: '' }
];

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']);

}

For those using Angular 5+, you CAN get router.navigate(['']) to reload the same URL. It's not well documented, and coming from a server heavy framework like .NET, this feels more natural.

Added runGuardsAndResolvers: 'always' to one of your paths and onSameUrlNavigation: 'reload' to the RouterModule initialization.

app-routing.module.ts

const routes: Routes = [
    { path: '' , component: HomeComponent, canActivate: [UserService], runGuardsAndResolvers: 'always' },
    { path: 'login', component: LoginComponent },
    { path: 'register', component: RegisterComponent },
    { path: '**' , redirectTo: '' }
];

@NgModule({
    imports: [RouterModule.forRoot(routes, {
        onSameUrlNavigation: 'reload'
    })],
    exports: [RouterModule]
})
export class AppRoutingModule { }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM