Reputation: 1828
I'm trying to detect the router deactivation.
Here's the router definition:
export const AppRoutes: Routes = [
{
path: '',
component: HelloComponent,
canDeactivate: [ConfirmDeactivateGuard]
},
{
path: 'error',
component: ErrorComponent,
canDeactivate: [ConfirmDeactivateGuard],
},
{
path: '**',
component: ErrorComponent,
canDeactivate: [ConfirmDeactivateGuard],
pathMatch: 'full',
}
];
export const AppRouting: ModuleWithProviders = RouterModule.forRoot(AppRoutes, {
enableTracing: true,
});
And this is my deactivate guard service:
@Injectable()
export class ConfirmDeactivateGuard implements CanDeactivate<HelloComponent> {
canDeactivate(target: HelloComponent) {
// This code is never called. Why?
return window.confirm('wtf?' || 'Are you sure?');
}
}
When I try to go from to root url('/') to some other url, I expect to see the window confirmation. However, it is not happening. Do you have any ideas or do you catch anything missing?
If you want to see the code online, check the link below:
https://stackblitz.com/edit/angular-vw9b7u?file=src%2Fapp%2FdeactivateGuard.ts
Upvotes: 2
Views: 2597
Reputation: 34465
You need to add the guard to the module's providers
providers: [ConfirmDeactivateGuard],
Here is a modified stackblitz demo
Edit: that guard is not triggered from direct navigation, i.e. when you type in directly the URL in the adressbar. The guard in only triggered for navigation within the angular app (see here). You could use beforeunload
event as a workaround
Upvotes: 3
Reputation:
Maybe that if you provided the guard in the module's provider and proposed a way of navigating, it would work ...
Upvotes: 0