How to get target route in ng2 guard canActivate?

送分小仙女□ 提交于 2019-12-11 08:02:49

问题


How can I get the route which the user is trying to open within an canActivate guard in angular 2?

How can I make the guard watch for every route parameter change eg. a change of the id within the route?

import { Injectable }       from '@angular/core';
import {Observable, Observer, Subject} from "rxjs/Rx";

@Injectable()
export class RightsGuard implements CanActivate {
    constructor(
      private router: Router,
      private route: ActivatedRoute
      // private state: RouterStateSnapshot
    ) { }

    canActivate(): Observable<boolean> | boolean {
      var targetUrl = ???
      // var targetUrl = this.router.url // is showing previous url?
      return true;
    }
}

Suggested answer in Angular 2 get current route in guard using private state: RouterStateSnapshot and then this.route.url does not work for me, since it throws an DI error:

Error: Uncaught (in promise): Error: DI Error
Error: DI Error

回答1:


The following seems to work, however route and state must not be injected in the constructor since this causes errors.

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
  console.log("route-access",state);
}

However this results in the problem that the guard is only called once for each route. For changes of route parameters like :id the guard is not being invoked. But this seems to correlate with a bug in the 3.2 router:

  • Calling angular2 route guard multiple times
  • https://github.com/angular/angular/issues/12851


来源:https://stackoverflow.com/questions/42171356/how-to-get-target-route-in-ng2-guard-canactivate

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