ZeroCool
ZeroCool

Reputation: 629

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

Upvotes: 9

Views: 3942

Answers (2)

dweep
dweep

Reputation: 111

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

Upvotes: 11

j2L4e
j2L4e

Reputation: 7060

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.

Upvotes: 4

Related Questions