Angular 2 получить текущий маршрут в страхе
У меня есть класс AccessGuard в моем проекте, его работа заключается в том, чтобы определить, может ли пользователь получить доступ к маршруту или нет. Я использовал router.url
для получения текущего маршрута, но URL-адрес возвращает маршрут до перехода на новый маршрут, так как я нахожусь в маршруте пользователей, и я нажимаю на маршрут кандидатов, поэтому URL-адрес возвращает пользователей вместо кандидатов, которые я хочу, чтобы для проверки доступа к маршруту
это мой файл маршрута:
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;
}
Ответы
Ответ 1
Вам нужно использовать параметры метода для просмотра целевого маршрута:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
console.log(state.url);//'candidates'
}
canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot)
Ответ 2
это может вам помочь:
-
Импортировать ActivatedRouteSnapshot и RouterStateSnapshot:
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
-
Подпись в canActivate:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable {}
-
Проверьте состояние :
console.log("route-access",state);
Ваш файл Guard будет выглядеть примерно так:
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
import { Observable } from 'rxjs';
import { AutenticacionService } from 'app/services/index';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private _router: Router, private auth:AutenticacionService) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<boolean> {
// console.log("route-access",state);
let _url:string="";
state.url.split("/").forEach(element => {
if(_url==="")
if(element!=="")
_url=element;
});
// console.log(_url);
return this.auth.check(_url)
.map((result) => {
if (result) {
return true;
} else {
this._router.navigate(['/']);
return false;
}
});
}
}