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

问题描述 投票:3回答:2

我有一种情况,当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:一般来说,有没有办法在初始化期间停止组件生命周期以允许抢先导航到安全的地方?

angular
2个回答
2
投票

你想要的是一名后卫。防护可用于防止导航到路线,或者您可以在这种情况下使用它们来截取和重定向。见https://angular.io/guide/router#milestone-5-route-guards


0
投票

目前,似乎Angular 2没有为应用程序提供中断(停止)组件生命周期和组件模板(以及子组件/模板)的呈现的机制。

一位同事建议在我父组件中的所有属性和所有相关的子组件属性上放置条件处理/呈现逻辑,以防止错误地访问组件中的undefined对象。这种方法肯定会起作用,但设置起来似乎相当繁琐,维护起来更加痛苦,所以我决定稍稍解决这个问题......

最终,我的方法是在我的父组件模板周围使用包装<div *ngIf="valid"></div>元素,并将每个从属子组件模板放在它们自己的包装<div *ngIf="valid"></div>元素中。这样做使我能够在undefined对象的情况下停止渲染模板。然后,我创建了一个服务,子组件监听该服务,并且父组件在父组件的有效实例化发生时发出信号(例如,不存在undefined对象)。

如果有人可能有更好的建议如何处理这种情况,请告诉我。

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