[英]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. 我试图弄清楚为什么下面的router.navigate([''])代码不会将用户带到登录组件。 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. 以下是流程:用户访问站点并立即重定向到/ login,因为Route Guard失败。 If they login, Route Guard passes and they go to [' '] which is the HomeComponent. 如果他们登录,Route Guard会通过,然后他们会转到['']这是HomeComponent。 Then when they click logout I figure the navigate to [' '] should fail and simply go to /login. 然后,当他们点击退出时,我认为导航到['']会失败,只需转到/ login。 For some reason it stays on the HomeComponent and never navigates. 由于某种原因,它停留在HomeComponent上,从不导航。
home.component.ts home.component.ts
logout() {
this.userService.logout();
this.router.navigate(['']);
}
user.service.ts 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 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. 您可以在注销时调用'this.router.navigate(['/ login'])'。
logout() {
this.userLoggedIn = false;
this.router.navigate(['/login']);
}
For those using Angular 5+, you CAN get router.navigate(['']) to reload the same URL. 对于使用Angular 5+的用户,可以使用router.navigate(['']) 重新加载相同的URL。 It's not well documented, and coming from a server heavy framework like .NET, this feels more natural. 它没有很好的文档记录,并且来自像.NET这样的服务器重型框架,这感觉更自然。
Added runGuardsAndResolvers: 'always' to one of your paths and onSameUrlNavigation: 'reload' to the RouterModule initialization. 添加了runGuardsAndResolvers:'always'到你的一个路径和onSameUrlNavigation:'reload'到RouterModule初始化。
app-routing.module.ts 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 { }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.