所以,我试图通过使用警卫来保护对多条路线的访问。我正在使用以下路线这样做:
const adminRoutes : Routes = [
{
path: 'admin',
component: AdminComponent,
canActivate: [ AuthGuardService ],
children : [
{
path: '',
canActivateChild: [ AuthGuardService ],
children: [
{ path: 'edit', component: DashboardComponent},
{ path: '', component: DashboardComponent}
]
}
]
}
];
看看是什么AuthGuardService
样子的
import { Injectable } from '@angular/core';
import {CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot} from "@angular/router";
@Injectable()
export class AuthGuardService implements CanActivate{
constructor(private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
console.log("Guarding...");
return this.sessionValid();
}
canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
console.log("Guarding children...");
return this.canActivate(route, state);
}
sessionValid() : boolean {
//tests
}
}
canActivate
当我尝试仅使用(已注释)访问“/admin”和“/admin/edit”时canActivateChild
,控制台显示
Guarding...
当我移除canActivate
并canActivateChild
带回控制台显示
Guarding children...
当我保留两者时,它会回到显示Guarding...
。所以,我的问题是什么canActivateChild
时候canActivate
保护根元素和子元素的目的是什么?
PS:我得到它canActivateChild
在子路由激活之前运行。但是这样做有什么好处呢?只保留其中一个还不够吗?