首页 文章

已经在Component上的Angular router.navigate w / route guard不工作

提问于
浏览
2

我试图弄清楚为什么下面的router.navigate([''])代码不会将用户带到登录组件 . 我只是留在家庭组件 . 当我添加调试器;在代码中它似乎进入某种无限循环 .

Here is the process: 用户来到站点并立即被重定向到/ login,因为Route Guard失败 . 如果他们登录,Route Guard会通过并转到[' '],这是HomeComponent . 然后,当他们点击退出时,我认为导航到[' ']应该失败,只需转到/ login . 由于某种原因,它停留在HomeComponent上,从不导航 .

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

1 回答

  • 1

    为什么它应该导航它已经在['']并且你再问一次去['']?您可以在注销时调用'this.router.navigate(['/ login'])' .

    logout() {
       this.userLoggedIn = false;
       this.router.navigate(['/login']);
    
    }
    

相关问题