2

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

ankakusu
  • 1,738
  • 8
  • 26
  • 37

2 Answers2

3

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

David
  • 33,444
  • 11
  • 80
  • 118
  • You are right that the provider was missing. But, it is not still working if we want to change the url from the address bar. – ankakusu Aug 02 '18 at 12:22
  • @ankakusu I edited my answer. The guard is not the right option fif you also want to be notified of address bar navigation – David Aug 02 '18 at 13:08
0

Maybe that if you provided the guard in the module's provider and proposed a way of navigating, it would work ...

Stackblitz