我正在尝试使用 canDeactivate 路由器防护。我传入的组件 (ClaimsViewComponent) 在代码第一次运行时为空。但在随后的运行中,代码按预期运行。我们试图弄清楚为什么组件在第一次运行时为空。
这是 canDeactivate 保护代码:
@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;
}
}
这是路由模块代码:
const routes: Routes = [
{ path: ':type', component: ClaimsViewComponent, canDeactivate:
[ConfirmDeactivateGuard] }
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
这是完整的错误堆栈:
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)
谢谢你。