【发布时间】:2018-05-23 01:26:49
【问题描述】:
我有一个带有子路由器的路由器。父路由器有一个组件。在该组件中,我检查一个条件,如果它失败,我会重定向。问题是子路由器组件 ngOnInit 代码被执行。有什么办法可以防止。
const routes: Routes = [
{
path: 'parent/:id',
component: ParentComponent,
children: [
{
path: 'child',
component: ChildComponent
}
]
}
];
class ParentComponent implements OnInit {
readonly NUMBER_REGEX = /^\+?\d+$/;
ngOnInit() {
this.route.params.subscribe( params => {
if (params.id) {
if (!this.NUMBER_REGEX.test(params.id)) {
this.router.navigateByUrl('/not-found');
}
}
});
}
}
class ChildComponent implements OnInit {
ngOnInit() {
console.log('don\'t want this to work on /parent/string/child but still works');
}
}
我知道我可以使用服务在组件之间传递数据。但我想要更清洁的解决方案。
【问题讨论】:
-
如果页面不应该被加载,你不应该加载你的父组件。我的意思是,您应该在实际加载页面(或导航到页面)之前检查您的状况。
标签: angular