How to get target route in ng2 guard canActivate?
Asked Answered
B

1

2

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
Beckner answered 11/2, 2017 at 1:55 Comment(0)
B
4

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:

Beckner answered 11/2, 2017 at 13:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.