我有一个包含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
。这是一个问题,因为我也需要保护根路由/
。
更新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']);
}
}
答案 0 :(得分:0)
您必须调整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);
}
}