为什么警卫不保护根路由,只保护孩子? [英] Why guard doesn't protect root route, only children?
本文介绍了为什么警卫不保护根路由,只保护孩子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含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-list
和phone-list
。这是一个问题,因为我还需要保护根路由/
。
更新1AuthGuard
@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
您必须调整推荐答案。它的父级和子级都需要CanActivate-Method和CanActivateChild-Method。
@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);
}
}
这篇关于为什么警卫不保护根路由,只保护孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文