手动更改URL时Angular 4 Routeguard不工作

手动更改URL时Angular 4 Routeguard不工作,angular,authentication,Angular,Authentication,我的angular 4应用程序有几个路线: const appRoutes: Routes = [ { path: '', component: MainMenuComponent, canActivate: [AuthGuard] }, { path: 'Content', component: ContentComponent, canActivate: [AuthGuard] }, { path: 'Organisations', component: Organisation

我的angular 4应用程序有几个路线:

const appRoutes: Routes = [
  { path: '', component: MainMenuComponent, canActivate: [AuthGuard] },
  { path: 'Content', component: ContentComponent, canActivate: [AuthGuard] },
  { path: 'Organisations', component: OrganisationComponent, canActivate: [AuthGuard] },
  { path: 'Licenses', component: LicenseComponent, canActivate: [AuthGuard] },
  { path: 'Logs', component: LogsComponent, canActivate: [AuthGuard] },
  { path: 'Community', component: CommunityComponent, canActivate: [AuthGuard] },
  { path: 'Profile', component: ProfileComponent, canActivate: [AuthGuard] },
  { path: 'Signup', component: SignupComponent },
  { path: 'Login', component: SigninComponent },
  { path: 'Landing', component: LandingPageComponent},
  { path: '**', component: MainMenuComponent , canActivate: [AuthGuard]}, // Page not Found
];
带有[AuthGuard]的每个页面只能由经过身份验证的用户激活

AuthGuard看起来像这样:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

if  (this.authService.isAuthenticated)
{
  return true;
}
else
{
  this.router.navigate(['Landing']);
}
如果用户经过身份验证,则可以访问该路由,如果没有,则将用户重定向回登录页

当按下网站上通向某些路线的按钮时,例如:

<a routerLink="/Content"> Content</a>
内容
身份验证工作没有问题,但是当我在URL栏中手动键入路由时,用户总是被重定向回登录页,即使他已通过身份验证


我正在试图理解为什么会发生这种情况,并找出解决方法。

可能您的authService是异步的,或者会话未保存在本地存储中,当您尝试通过URL手动获取页面时,您的angular guard没有保存当前用户

试试这个:

  • 更改canActivate方法以使用承诺

  • 将会话保存在本地存储或Cookie中,并在初始化站点时恢复会话(如果存在)


canActivate(路由:ActivatedRouteSnapshot,状态:RouterStateSnashot):承诺{
返回新承诺((解决、拒绝)=>{
//检查authService是否返回可观察或承诺
/**
如果返回对此的承诺更改:
this.authService.isAuthenticated.then((isAuth)=>{
if(isAuth){
决心(正确);
}否则{
这个.router.navigate(['Landing']);
}
})
*/
/**
如果返回此项的可观察更改:
this.authService.isAuthenticated.subscribe((isAuth)=>{
if(isAuth){
决心(正确);
}否则{
这个.router.navigate(['Landing']);
}
})
*/
if(this.authService.isAuthenticated){
决心(正确);
}否则{
这个.router.navigate(['Landing']);
}
})
}

服务在页面刷新时不会持久存在。您可以尝试使用本地存储或会话存储。