我试图为不同的孩子使用相同的组件(SigninFormComponent
)(下面的代码中的confirm
)我在这里面临的是,只要子路由处于活动状态,代码工作正常,一旦我切换回我收到的父路由这个错误,
TypeError:无法读取null的属性'params'
错误是显而易见的,但如何在不抛出错误的情况下进行检查?
我的路线配置,
......
{ path: 'web', component: WebsiteHomeComponent, children: [
{ path: 'welcome', component: WebsiteWelcomeComponent },
{ path: 'signin', component: SigninFormComponent, children: [
{path: ':confirm', component: SigninFormComponent}
] }, .....
我想以这种方式检查,
ngOnInit() {
if (this.activatedRoute.snapshot.firstChild.params['confirm']) {
this.subscription = this.activatedRoute.queryParams.subscribe(
(param: Params) => {
this.confirmUserId = param['userId'];
this.confirmUserIdCode = param['code'];
this.ConfirmEmailAddress();
});
}
this.loginForm = new FormGroup({
'uniqueId': new FormControl(null, [Validators.required]),
'password': new FormControl(null, Validators.required),
'rememberMe': new FormControl(false)
});
}
现在我只是通过搜索url匹配字符串来解决它,
if (routeUrl.indexOf('confirm') > -1) {
......
}
if(this.activatedRoute.snapshot.firstChild && this.activatedRoute.snapshot.firstChild.params['confirm']) {
这样this.activatedRoute.snapshot.firstChild.params['confirm']
只检查当this.activatedRoute.snapshot.firstChild
是truthy(null
是假的)