【问题标题】:Angular 4 Routeguard not working when manually changing URL手动更改 URL 时 Angular 4 Routeguard 不起作用
【发布时间】: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 栏中手动输入路由时,即使用户通过了身份验证,用户总是会被重定向回登录页面。

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

【问题讨论】:

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

标签: angular authentication


【解决方案1】:

也许您的 authService 是异步的,或者会话未保存在 localStorage 中,并且当您尝试通过 URL 手动获取页面时,您的 Angular 防护没有保存当前用户。

试试这个:

  • 更改 canActivate 方法以使用 Promise

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

 
 canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
    return new Promise((resolve, reject) => {
    
    // Check if the authService returns an Observable or a Promise
    
    /**
      if returns a promise change for this:
      
      this.authService.isAuthenticated.then((isAuth) => {
        if  (isAuth) {
          resolve(true);
        } else {
          this.router.navigate(['Landing']);
        }
      })
      
      */
      
      /**
       if returns a Observable change for this:
      
      this.authService.isAuthenticated.subscribe((isAuth) => {
        if  (isAuth) {
          resolve(true);
        } else {
          this.router.navigate(['Landing']);
        }
      })
      */
      if  (this.authService.isAuthenticated) {
        resolve(true);
      } else {
        this.router.navigate(['Landing']);
      }
   
     
    })
 }
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-25
    • 2017-10-10
    • 1970-01-01
    相关资源
    最近更新 更多