我有一种情况,当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:一般来说,有没有办法在初始化期间停止组件生命周期以允许抢先导航到安全的地方?
你想要的是一名后卫。防护可用于防止导航到路线,或者您可以在这种情况下使用它们来截取和重定向。见https://angular.io/guide/router#milestone-5-route-guards
目前,似乎Angular 2没有为应用程序提供中断(停止)组件生命周期和组件模板(以及子组件/模板)的呈现的机制。
一位同事建议在我父组件中的所有属性和所有相关的子组件属性上放置条件处理/呈现逻辑,以防止错误地访问组件中的undefined
对象。这种方法肯定会起作用,但设置起来似乎相当繁琐,维护起来更加痛苦,所以我决定稍稍解决这个问题......
最终,我的方法是在我的父组件模板周围使用包装<div *ngIf="valid"></div>
元素,并将每个从属子组件模板放在它们自己的包装<div *ngIf="valid"></div>
元素中。这样做使我能够在undefined
对象的情况下停止渲染模板。然后,我创建了一个服务,子组件监听该服务,并且父组件在父组件的有效实例化发生时发出信号(例如,不存在undefined
对象)。
如果有人可能有更好的建议如何处理这种情况,请告诉我。