angular - 如何停止 Angular 2 组件初始化并导航到默认(安全)路由

标签 angular

我遇到这样一种情况,当 Component 正在初始化时,组件检测到应用程序未处于组件无法正确加载/运行的正确状态。组件的 ngOnInit 方法尝试将 navigate() 到安全页面,以防止由于在模板中访问 undefined 对象的成员而导致彻底失败。

ngOnInit() {
  // when no scenario has been passed to the component:
  // try to get the active one from the application context via the scenario service

  if (null == this.scenario) {

    this.scenario = this.scenarioService.activeScenario;

    // when there's no current scenario set in the application context:
    // try to get one from the scenario service in the active period

    if (null == this.scenario) { 

      this.scenario = this.scenarioService.getScenariosByYear(this.settingsService.activePeriod)[0];

      // when there's no scenarios defined in the active period:
      // navigate to the the scenario manager component so the user can create one

      if (null == this.scenario) {

        this.router.navigate(['/scenario']); // <==== this doesn't seem to fire

      }
    }
  }
}

问题 1:为什么 this.router.navigate(['/scenario']); 调用不起作用(中断组件生命周期)?

问题 2:一般来说,有没有一种方法可以在初始化期间停止组件生命周期以允许抢先导航到安全位置?

最佳答案

你想要的是一个守卫。 Guards 可用于阻止导航到路由,或者您可以在这种情况下使用它们来拦截和重定向。参见 https://angular.io/guide/router#milestone-5-route-guards

关于angular - 如何停止 Angular 2 组件初始化并导航到默认(安全)路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41061986/

相关文章:

angular - Angular2 稳定版中的 md-input 绑定(bind)错误

Angular 7 : Async validator change detection

html - Angular Navbar Menu - 将菜单项与子菜单对齐

testing - angular2 测试 : Can't bind to 'ngModel' since it isn't a known property of 'input'

angular - MAT_DATE_FORMATS 字段的定义/含义

Angular 4 参数与 json stringify

node.js - 在 Angular2 中保护 API key

angular - 为什么我们在 Angular 的组件中传递数组中的样式?

angular - Nginx for Angular没有达到后端api

forms - 手动设置 FormBuilder 控件的值