停止儿童导航角度路由器

时间:2018-05-22 17:19:00

标签: angular

我有一台有子路由器的路由器。父路由器有一个组件。在该组件中,我检查一个条件,如果它失败,我重定向。问题是子路由器组件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');
  }
}

我知道我可以使用服务在组件之间传递数据。但我想要更清洁的解决方案。

1 个答案:

答案 0 :(得分:1)

是的,如果符合(或不符合)某些条件,请使用RouteGuard防止路由

RouteGuard正是为此目的

https://angular.io/guide/router#milestone-5-route-guards