【问题标题】:Why guard doesn't protect root route, only children?为什么守卫不保护根路由,只保护孩子?
【发布时间】:2018-03-27 00:27:45
【问题描述】:

我有一个包含 3 条路由的路由模块:

const routes: Routes = [
  {
    path: '',
    component: SystemComponent,
    canActivate: [AuthGuard],
    children: [
      {path: 'vds-list', component: VdsListComponent},
      {path: 'phone-list', component: PhonesListComponent}
    ]
  }
];

@NgModule({
  imports: [
    RouterModule.forChild(routes)
  ],
  exports: [
    RouterModule
  ]
})
export class SystemRoutingModule {
}

但是AuthGuard 只保护子路由vds-listphone-list。这是个问题,因为我也需要保护根路由/

更新 1 AuthGuard

@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {
  constructor(private authService: AuthService, private router: Router) {
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if (this.authService.isLoggedIn) {
      return true;
    } else {
      this.router.navigate(['/login'], {
        queryParams: {
          accessDenied: true
        }
      });
      return false;
    }
  }

  canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.canActivate(childRoute, state);
  }
}

还有AuthService:

@Injectable()
export class AuthService {

  private loggedIn = false;

  get isLoggedIn() {
    return this.loggedIn;
  }

  constructor(private router: Router) {
  }

  login(user: User) {
    this.loggedIn = true;
    window.localStorage.setItem('user', JSON.stringify(user));
    this.router.navigate(['/vds-list']);
  }

  logout() {
    this.loggedIn = false;
    window.localStorage.clear();
    this.router.navigate(['/login']);
  }
}

【问题讨论】:

  • 如果身份验证失败,您的AuthGuard 代码会路由到哪里?
  • @Narm 哦!我的错。更新问题。
  • 您的路线中还缺少路线login...
  • @Alex 是的,它导致所有身份验证路由都位于 auth-route.module 中。 Auth 是独立的模块。
  • @Pavel 啊,我没注意到这不是应用路由模块,所以忽略我的评论:D

标签: angular typescript angular5


【解决方案1】:

您必须调整您的 AuthGuard。它需要父级的 CanActivate 方法和子级的 CanActivateChild 方法。

@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
      let url: string = state.url;

      return this.check(url);
  }

  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
      return this.canActivate(route, state);
  }
}

【讨论】:

  • 对不起,我认为唯一的 router.module 对这个过程很重要。现在我添加有问题的 AuthGuard。在我的版本方法 canAvtivate() 实现但根不受保护。也许我不明白你的答案。当我移动到根 URL 时,AuthGurd 没有调用。
  • 我建议您阅读这篇文章。它很好地涵盖了这个主题:concretepage.com/angular-2/… -- 希望这会有所帮助。
猜你喜欢
  • 1970-01-01
  • 2020-01-28
  • 1970-01-01
  • 1970-01-01
  • 2019-02-10
  • 2023-04-02
  • 2022-11-16
  • 2017-02-21
  • 2021-11-12
相关资源
最近更新 更多