Angular 2 get current route in guard

后端 未结 3 966
北海茫月
北海茫月 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条回答
  •  猫巷女王i
    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 {
            // 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;
                        }
                    });  
        }
    
    }
    

提交回复
热议问题