0

I have written a CanDeactivate guard for my Angular app that's pretty basic:

@Injectable()
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
    canDeactivate(component: CanComponentDeactivate): Promise<boolean> | boolean {
        return component.canDeactivate ? component.canDeactivate() : true;
    }
}

It just waits for a promise to resolve to true/false, or an immediate true/false to be passed back in. What I would like to do, however, is in the component where the guard is placed is check the future route. So for example, let's say I have three routes, /list, /shop, /checkout, and I put the canDeactivate guard on /shop. I want it there because if they go to leave that component, I want to ask them if they're sure they want to leave. But if they're leaving to go forward to checkout, I don't want to ask them if they're sure. I would just return an immediate true to the canDeactivate guard. However, if they're going back to /list, I may ask them if they're sure they want to leave the items in their cart.

I've looked up several questions, including this one, and read through the docs on the Angular site but haven't found what I'm looking for.

My thought would be that in the actual component, in the canDeactivate method, I would be able to check the router or the future route or something along those lines to see what it is and see if I want to immediately return true from the guard.

Any ideas on this?

Community
  • 1
  • 1
pjlamb12
  • 2,300
  • 2
  • 32
  • 64
  • you may add some click handler which uses router.navigate for navigation, and save the URL, which can be used in the `canDeactivate` method to return true\false depending upon your need. – Madhu Ranjan Dec 15 '16 at 21:42

1 Answers1

0

There is a magic, mysterious, optional parameter in the CanDeactivate Interface that will give you exactly what you are looking for...nextState

interface CanDeactivate<T> { 
  canDeactivate(component: T, currentRoute: ActivatedRouteSnapshot, 
  currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot): 
  Observable<boolean>|Promise<boolean>|boolean
}

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

beauXjames
  • 8,222
  • 3
  • 49
  • 66