I'm trying to use the canDeactivate router guard. The component I'm passing in (ClaimsViewComponent) is null the first time the code runs. But on subsequent runs, the code runs as expected. We're trying to figure out why the component is null on first run.
This is the canDeactivate guard code:
@Injectable()
export class ConfirmDeactivateGuard implements
CanDeactivate<ClaimsViewComponent> {
canDeactivate(target: ClaimsViewComponent): boolean {
if (target.canDeactivate()) {
return window.confirm('Do you really want to cancel?');
}
return true;
}
}
This is the routing module code:
const routes: Routes = [
{ path: ':type', component: ClaimsViewComponent, canDeactivate:
[ConfirmDeactivateGuard] }
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
Here is the full error stack:
TypeError: Cannot read property 'canDeactivate' of null
at ConfirmDeactivateGuard.canDeactivate (confirm-deactivate-guard.ts:16)
at MergeMapSubscriber.eval [as project] (router.js:3933)
at MergeMapSubscriber._tryNext (mergeMap.js:128)
at MergeMapSubscriber._next (mergeMap.js:118)
at MergeMapSubscriber.Subscriber.next (Subscriber.js:95)
at ArrayObservable._subscribe (ArrayObservable.js:116)
at ArrayObservable.Observable._trySubscribe (Observable.js:172)
at ArrayObservable.Observable.subscribe (Observable.js:160)
at MergeMapOperator.call (mergeMap.js:92)
at Observable.subscribe (Observable.js:157)
at ConfirmDeactivateGuard.canDeactivate (confirm-deactivate-guard.ts:16)
at MergeMapSubscriber.eval [as project] (router.js:3933)
at MergeMapSubscriber._tryNext (mergeMap.js:128)
at MergeMapSubscriber._next (mergeMap.js:118)
at MergeMapSubscriber.Subscriber.next (Subscriber.js:95)
at ArrayObservable._subscribe (ArrayObservable.js:116)
at ArrayObservable.Observable._trySubscribe (Observable.js:172)
at ArrayObservable.Observable.subscribe (Observable.js:160)
at MergeMapOperator.call (mergeMap.js:92)
at Observable.subscribe (Observable.js:157)
at resolvePromise (zone.js:814)
at resolvePromise (zone.js:771)
at eval (zone.js:873)
at ZoneDelegate.invokeTask (zone.js:421)
at Object.onInvokeTask (core.js:4740)
at ZoneDelegate.invokeTask (zone.js:420)
at Zone.runTask (zone.js:188)
at drainMicroTaskQueue (zone.js:595)
Thank you.
I fixed this issue by adding the canDeactivate inside my page.module.ts instead of app.module.ts
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With