【问题标题】:Stop Child Navigation Angular router停止子导航角路由器
【发布时间】:2018-05-23 01:26:49
【问题描述】:

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

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

【问题讨论】:

  • 如果页面不应该被加载,你不应该加载你的父组件。我的意思是,您应该在实际加载页面(或导航到页面)之前检查您的状况。

标签: angular


【解决方案1】:

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

RouteGuards 正是为此目的

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

【讨论】:

    猜你喜欢
    • 2019-09-27
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    • 2020-02-25
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多