我有一个Angular应用程序,其中包含实现canLoad: [AuthGuard]
的路由,而canLoad在我的AuthGuard类中是这样的:
canLoad(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
boolean
{
if (this.authService.isLogged || this.authService.checkLoggedIn())
{
return true;
} else
{
this.router.navigate(['/login']);
return
}
}
如果我在未登录的情况下尝试访问我的任何路由,我会不断收到错误,因为路由的组件仍然运行NgOnInit()
而没有任何路由信息,因此我最终进行没有参数的API调用。但是,该页面始终导航到/login
。
我对AuthGuard的工作原理并不十分清楚,但是我在canLoad()
函数上设置断点并且它们不会被触发。我在这里做错了吗?
这是有问题的根路线:
{
path: '',
component: MydocsComponent,
canLoad: [AuthGuard],
children: [...]
}
编辑:我已经意识到这是我的this.authService.checkLoggedIn()
方法的问题 - 即它会在被AuthGuard检查之前将用户重定向到/login
,所以这是我的问题。感谢您的帮助,我希望下面的答案可以帮助一些人使用canLoad
。
canLoad
与lazily-loaded
模块一起使用,以防止在条件失败时加载块。如果要限制对组件的访问,请使用canActivate
guard。
检查这个summary