TypeError:无法读取null的属性'canDeactivate'

时间:2018-07-20 21:01:34

标签: angular-router-guards

我正在尝试使用canDeactivate路由器防护。第一次运行代码时,我传入的组件(ClaimsViewComponent)为null。但是在随后的运行中,代码将按预期运行。 我们试图弄清楚为什么第一次运行时该组件为空。

这是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)

谢谢。

2 个答案:

答案 0 :(得分:0)

似乎canDeactivate不能用于“延迟加载”。请检查您的路线,并确保已设置component属性。

答案 1 :(得分:0)

我通过在我的page.module.ts而不是app.module.ts中添加canDeactivate来解决此问题