因此,我試圖通過使用警衛來保護對幾條路線的訪問。我使用以下途徑可以這樣做:試圖瞭解CanActivate和CanActivateChild之間的區別
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
(canActivateChild
被註釋掉)的控制檯顯示
Guarding...
當我刪除canActivate
,並把canActivateChild
回控制檯DISPLA ys
Guarding children...
當我保持這兩者時,它會返回到顯示Guarding...
。 所以,我的問題是canActivate
保護根元素和孩子時,有什麼目的canActivateChild
?
PS:我知道canActivateChild
在孩子路線被激活之前運行。但是,這有什麼好處?是不是隻保留其中一個足夠?
我們不能只使用canActivate而不是canActivateChild嗎? – YounesM
也許,這取決於您的要求。我上面給出的例子可能有點太過於人爲設計。 'canActivateChild'在每個子路由被激活之前運行。你確實可以使用'canActivate'來保護一個所有孩子的根組件,但是你可能有孩子,某些用戶不需要查看他們何時需要能夠看到根組件。例如,您可以將一些管理組件中的數據添加到大多數或所有用戶需要到達根目錄的Feature模塊中,但不一定是某些路由的子模塊。 –