如何检查第一个孩子是否在一个网址中参与而不在Angular中抛出null错误?

问题描述 投票:1回答: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) {
      ......
}
angular angular5
1个回答
1
投票
if(this.activatedRoute.snapshot.firstChild && this.activatedRoute.snapshot.firstChild.params['confirm']) {

这样this.activatedRoute.snapshot.firstChild.params['confirm']只检查当this.activatedRoute.snapshot.firstChild是truthy(null是假的)

© www.soinside.com 2019 - 2024. All rights reserved.