Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 How can I get destination URL in a Guard?

I am trying to create a CanDeactivate guard, to prompt "save changes" to the user when he navigates away from the route. There are some routes that I would like to exclude (lets say when user switches tabs, but doesnt choose a new item). I've been really struggling in understanding how can I get the destination URL without using some sort of navigation service and just keep the full URL there. Here is my signature for can deactivate

 // This is what handles the deactivate
public canDeactivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {

All of the 'route' and 'state' object contain the previous URL and no information about the destination URL.

I trigger the navigation in another component with

this._router.navigate(['/clients', this.selectedClient.id, page]);
like image 431
ZeroCool Avatar asked Sep 12 '16 13:09

ZeroCool


2 Answers

Actually destination state is one of the parameter of CanDeactivate.

canDeactivate(
    component: CanComponentDeactivate,
    route: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot,
    nextState: RouterStateSnapshot
    ):  Observable<boolean>|Promise<boolean>|boolean {

    return true;
}

Reference: https://angular.io/api/router/CanDeactivate

like image 131
dweep Avatar answered Oct 20 '22 13:10

dweep


You can subscribe to the router's events:

NavigationStart should fire before CanDeactivate, so you can grab the destination.

routingDestination: string = "";
constructor(router:Router) {
  router
    .events
    .filter(e:Event => e instanceof NavigationStart)
    .subscribe((e: NavigationStart) => this.routingDestination = e.url)
  }
}

That aside, I think needing to know the destination in CanDeactivate is kind of a design flaw. But as I don't know your app, this might actually be the right way.

like image 32
j2L4e Avatar answered Oct 20 '22 12:10

j2L4e