我遇到这样一种情况,当 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/