我的項目中有一個AccessGuard類,它的工作是確定用戶是否可以訪問路線。我使用router.url
獲取當前路線,但url返回導航到新路線之前的路線,例如我在用戶路線中,然後單擊候選路線,以便網址返回用戶而不是我希望驗證的候選路線訪問路線 這是我的路由文件:Angular 2獲得當前防護路線
const routes:Routes = [
{
path:'',
component:PanelComponent,
canActivate:[AuthGuard,AccessGuard],
canActivateChild:[AuthGuard,AccessGuard],
children:[
{
path:'dashboard',
component:DashboardComponent
},
{
path:'users',
component:UsersComponent
},
{
path:'users/:id',
component:ShowUserComponent
},
{
path:'candidates',
component:CandidatesComponent
},
{
path:'permissions',
component:PermissionsComponent
},
{
path:'holidays',
component:HolidaysComponent
},
{
path:'candidate/:id',
component:CandidateComponent
},
{
path:'salary/create',
component:InsertSalaryComponent
},
{
path:'document/create',
component:InsertDocumentComponent
},
{
path:'leave/create',
component:InsertLeaveComponent
}
]
}
];
,這是我訪問後衛:
permissions;
currentRoute;
constructor(private authService:AuthService,private router:Router){
this.permissions = this.authService.getPermissions();
}
canActivate(){
return this.checkHavePermission();
}
canActivateChild(){
console.log(this.router.url);
return this.checkHavePermission();
}
private checkHavePermission(){
switch (this.router.url) {
case "/panel/users":
return this.getPermission('user.view');
case '/panel/dashboard':
return true;
case '/panel/candidates':
return this.getPermission('candidate.view');
default:
return true;
}
}
getPermission(perm){
for(var i=0;i<this.permissions.length;i++){
if(this.permissions[i].name == perm){
return true;
}
}
return false;
}
我只是有問題,我刪除從參數和的ActivatedRouteSnapshot state.url返回一個數組,但如果ActivatedRouteSnapshot在參數中,它傳遞的是實際的url爲什麼? –
即使您只想使用RouterStateSnapshot參數,也不應從參數中刪除ActivatedRouteSnapshot。參數由位置定義。第一個參數始終是ActivatedRouteSnapshot,它的url字段是一個數組。第二個參數將始終是RouterStateSnapshot參數,它的url字段是一個字符串。希望能幫助到你。 –
要小心:如果你的url有queryparams,你可能必須這樣做:'console.log(state.url.substring(0,state.url.indexOf(「?」)));' –