Angular 2获得后卫

时间:2016-09-28 12:15:34

标签: angular angular2-routing angular2-guards

我的项目中有一个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;
}

3 个答案:

答案 0 :(得分:38)

您需要使用方法参数来查看目标路线:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
  console.log(state.url);//'candidates'
}

canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot)

答案 1 :(得分:3)

这可以帮到你:

  1. 导入 ActivatedRouteSnapshot RouterStateSnapshot

    import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';

  2. canActivate 中的签名:

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable {}

  3. 检查状态

    console.log("route-access",state);

  4. 你的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;
                        }
                    });  
        }
    
    }
    

答案 2 :(得分:0)

可以从RouterStateSnapshot返回当前URL,如下所示,

    import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';    

    canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot){
      console.log(state.url);  
      ...
    }