Angular 2 get current route in guard

雨燕双飞 提交于 2019-11-30 04:39:42

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)

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;
                    }
                });  
    }

}

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);  
      ...
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!