Issue
I’m trying to intercept a route change by router guard. So when I call:
this.router.navigate([“myApp/userProfiles”]);
So once called it goes through guard CanDeactivate interface. And the guard needs to determine where it’s really going to redirect.
So is there a property something like:
this.router.newRoute ??
Or should I use a global variable to set it before call navigate method?
Solution
As you can see in the CanDeactivate
interface the fourth argument is the nextState
. You can inspect it to find the next route’s url.
interface CanDeactivate<T> {
canDeactivate(
component: T,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState?: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean
}
So in your case you can do something like this:
canDeactivate(
component: TeamComponent,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState: RouterStateSnapshot
): Observable<boolean>|Promise<boolean>|boolean {
if (nextState.url === '/interesting/path/') {
// do something
else {
return true;
}
}
Answered By – Tomasz Kula
Answer Checked By – Jay B. (AngularFixing Admin)