Is it possible to get the intended route in the CanDeactivate guard in Angular 2 RC5 router? I see an answer to a similar question about CanActivate (CanActivate), but that does not seem to work in the CanDeactivate guard.
The use case I have is as follows: User clicks on a "Home" link while in the middle of filling out a form serviced by a "FormComponent". The FormComponent has a CanDeactivate attached to it. I need to know that the user was attempting to go specifically to the "Home" route to decide on what I want to do in the CanDeactivate. Inspection of the ActivatedRouteSnapshot and RouterStateSnapshot objects in the CanDeactivate guard only show information about the route that the user is currently on, related to the FormComponent. Although I understand this couples the two components together, this is just an example here to understand whether this is possible to do.
You might not need the destination URL for the next route since you can return an
Observable<boolean>
to theCanDeactivate()
in the guard.When our guard is checked we trigger our check for changes in the component and return a filtered Observable back to the guard. (Filter it for just the "true" value - otherwise we won't be able to continue the navigation to our desired route afterwards!)
When our check passes, we may navigate - if not we can't.
So we maybe want to show our user two buttons. One to skip saving and navigate (
doNotSaveAndNavigate()
) and another one to save and continue his navigation (doSaveAndNavigate()
).. or any other help to guide him or her..some.component.ts
can-deactivate-guard.service.ts
(I guess you know how to setup the CanDeactivate for the Router but for the sake of completeness you'll find a usage example in the official docs)
FYI: If you rly just want to get the URL on
CanDeactivate()
failure, subscribe to therouter.events
and filter for theNavigationCancel
event like this:you may need to import:
and add the
router
to your constructor:Angular 4 introduced an extra optional parameter to the CanDeactivate interface.
You can see it here.
You can use it with either Observable, Promise or immediately return a boolean.
Example:
Discussed here.