尝试在Angular 4中使用嵌套路由时出现此错误:
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'component' of null
TypeError: Cannot read property 'component' of null
at PreActivation.webpackJsonp.../../../router/@angular/router.es5.js.PreActivation.traverseRoutes (http://localhost:4200/vendor.bundle.js:77976:71)
at http://localhost:4200/vendor.bundle.js:77954:19
at Array.forEach (native)
at PreActivation.webpackJsonp.../../../router/@angular/router.es5.js.PreActivation.traverseChildRoutes (http://localhost:4200/vendor.bundle.js:77953:29)
at PreActivation.webpackJsonp.../../../router/@angular/router.es5.js.PreActivation.traverseRoutes (http://localhost:4200/vendor.bundle.js:77985:22)
这是我的路由代码:
const appRoutes: Routes = [
{
path: '',
component: HomeComponent
},
{
path: 'sobre',
component: SobreComponent
},
{
path: 'c/:concurso', component: ConcursoItemComponent
, children: [
{
path: ':cargo',
component: CargoItemComponent,
children: [
{
path: ':disc',
component: DisciplinaItemComponent,
children: [{
path: ':assunto',
component: AssuntoItemComponent
}]
}
]
}
]
},
];
我要制定以下嵌套规则,每个规则都使用变量来通知每个路由的嵌套组件:
/
/c/:concurso/
/c/:concurso/:cargo/
/c/:concurso/:cargo/:disc/
/c/:concurso/:cargo/:disc/:assunto
在每个级别上,我将需要所有上部变量来正确查询API的相关对象。
谢谢你的帮助!
最佳答案
正如本文(https://angular-2-training-book.rangle.io/handout/routing/child_routes.html)所述,在处理子路由时,就像为应用程序的根定义路由器导出一样,您也必须为父组件(在本例中为ConcursoItemComponent)定义路由器导出。 CargoItemComponent和DisciplinaItemComponent)因此您有2个选项。
{
path: 'c/:concurso,
component: ConcursoItemComponent
},
{
path: 'c/:concurso/:cargo,
component: CargoComponent
},
{
path: 'c/:concurso/:cargo/:disc,
component: DisciplinaItemComponent
},
{
path: 'c/:concurso/:cargo/:disc/:assunto,
component: AssuntoItemComponent
}
这样,路由器将始终将组件插入应用程序根目录下的路由器导出。