首页 文章

如何检查第一个孩子是否在URL中没有在Angular中抛出null错误?

提问于
浏览
1

我试图为不同的孩子使用相同的组件( 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) {
      ......
}

1 回答

  • 1
    if(this.activatedRoute.snapshot.firstChild && this.activatedRoute.snapshot.firstChild.params['confirm']) {
    

    这样 this.activatedRoute.snapshot.firstChild.params['confirm'] 仅在 this.activatedRoute.snapshot.firstChild 真实时被检查( null 是假的)

相关问题