Angular 2 get current route in guard

后端 未结 3 937
北海茫月
北海茫月 2020-12-25 12:16

I have an AccessGuard class in my project which its work is to determine if user can access to the route or not. I used the router.url to get the current route

相关标签:
3条回答
  • 2020-12-25 12:29

    You need to use the method parameters to see the target route:

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
      console.log(state.url);//'candidates'
    }
    
    canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot)
    
    0 讨论(0)
  • 2020-12-25 12:31

    this could help you:

    1. Import ActivatedRouteSnapshot and RouterStateSnapshot:

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

    2. Signature in the canActivate:

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

    3. Check the state:

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

    Your Guard file would look something like this:

        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;
                        }
                    });  
        }
    
    }
    
    0 讨论(0)
  • 2020-12-25 12:47

    Current URL can be returned from RouterStateSnapshot as shown below,

        import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';    
    
        canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot){
          console.log(state.url);  
          ...
        }
    
    0 讨论(0)
提交回复
热议问题