【发布时间】:2017-11-30 19:05:25
【问题描述】:
我的 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 栏中手动输入路由时,即使用户通过了身份验证,用户总是会被重定向回登录页面。
我正在尝试了解为什么会发生这种情况并找出解决方法。
【问题讨论】:
-
服务不会在页面刷新时持续存在。您可以尝试使用本地存储或会话存储。