ankakusu
ankakusu

Reputation: 1828

CanDeactivate does not work

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

Answers (2)

David
David

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

user4676340
user4676340

Reputation:

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

Stackblitz

Upvotes: 0

Related Questions