如何检查 url 中的第一个 children 参数而不在 Angular 中抛出空错误?
How to check if first children params in a url without throwing null error in Angular?
我正在尝试对不同的 children(下面代码中的confirm
)使用相同的组件(SigninFormComponent
),我在这里面临的是只要 child 路由处于活动状态代码工作正常,一旦我切换回 parent 路由我收到此错误,
TypeError: Cannot read property 'params' of null
错误很明显,但我如何检查而不抛出错误?
我的路线配置,
......
{ 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
为真(null
为假)时才会检查 this.activatedRoute.snapshot.firstChild.params['confirm']
我正在尝试对不同的 children(下面代码中的confirm
)使用相同的组件(SigninFormComponent
),我在这里面临的是只要 child 路由处于活动状态代码工作正常,一旦我切换回 parent 路由我收到此错误,
TypeError: Cannot read property 'params' of null
错误很明显,但我如何检查而不抛出错误?
我的路线配置,
......
{ 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
为真(null
为假)时才会检查 this.activatedRoute.snapshot.firstChild.params['confirm']