尝试在Angular 4中使用nestet路由时出现此错误:
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 /:货物/
/ C /:concurso /:货物/:盘/
/ C /:concurso /:货物/:盘/:ASSUNTO
在每个级别上,我将需要所有上层变量来正确查询API的相关对象。
感谢您的帮助!
答案 0 :(得分:24)
正如本文(https://angular-2-training-book.rangle.io/handout/routing/child_routes.html)所述,在处理子路由时,就像为应用程序的根定义路由器出口一样,您必须为父组件定义路由器出口(在这种情况下) ConcursoItemComponent。技术上也是CargoItemComponent& DisciplinaItemComponent)所以你有两个选择。
{
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
}

这样路由器将始终将组件插入应用程序根目录的路由器插座
答案 1 :(得分:4)
只是想我为了那些偶然发现这一点的人的利益添加评论,原因与我一样。如果模板使用条件呈现,并且异步满足这些条件,则router-outlet不能位于条件标记内,因为框架可能会在条件满足之前尝试呈现标记。例如:
<div *ngIf="someAsyncCall()">
<header>{{some result from the async call}}</header>
<router-outlet></router-outlet>
</div>
可能 会失败,具体取决于异步调用的完成速度。在条件渲染中仅包括标记的静态部分总是更安全。如:
<div *ngIf="someAsyncCall()">
<header>{{some result from the async call}}</header>
</div>
<router-outlet></router-outlet>
我把整个页面包裹在一个忙碌的指示符中#34;这个指令几乎可以保证路由器插座不会一直无法使用。事后似乎显而易见,但...... ....
答案 2 :(得分:1)
如果有兴趣使用子级路由结构的人。您可以遵循此模型。我在ngx-breadcrumbs中找到了这个。
const myRoutes : Route[] = {
{
path: '',
component: HomeComponent
},
{
path: 'about',
component: AboutComponent
},
{
path: 'person',
children: [
{
path: '',
component: PersonListComponent
},
{
path: ':id',
component: PersonDetailComponent
}
]
},
{
path: 'folder',
children: [
{
path: '',
component: FolderComponent
},
{
path: ':id',
component: FolderComponent
}
]
}
};