I'm trying to implement a canDeactivate
guard. For that purpose I need to know the component Instance of the route I want to navigate to.
canDeactivate(
component: ComponentCanDeactivate,
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot,
nextState: RouterStateSnapshot
): Observable<boolean> {
return new Observable((observer: Observer<boolean>) => {
console.log('componet', component);
console.log('state', state);
console.log('nextstate', nextState);
this.routerService.doSomething(nextState, route);
observer.next(true);
});
}
I wonder wheter its possible to get the component from nextState? I tried something like this:
nextState.root.component
but it returns the AppComponent
to me, since that's not the name of the component I am navigating to.
How do I do this? Or should I get an instance in other way?
Edit:
i can see the Component Instance(NextComponent) in the developer terminal of my browser inside of RouterStateSnapshot -->
_root: TreeNode
url: "/Nextcomponent/15708/childcomponent"
_root: TreeNode
children: Array(1)
0: TreeNode
children: Array(1)
0: TreeNode
children: Array(1)
0: TreeNode
children: Array(1)
0: TreeNode
children: Array(1)
0: TreeNode
children: []
value: ActivatedRouteSnapshot
component: class NextComponent
^^^^^^^^^^^^^
But not able to get it inside my code.
I see 2 things:
new Observable()
, and and I don't see why you put your code inside an observable (you may just remove the Observable).canDeactivateMyFeatureGuard
in your component. You can make your component implement a genericAppCanDeactivateMyFeatureGuard
(where your guard is namedMyFeatureGuard
), which definescanDeactivateMyFeatureGuard
.Then you call this method in the guard.
It would look like this:
and the guard: