I have a situation where as a Component
is initializing the component detects that the application is not in the proper state for the component to correctly load/operate. The component's ngOnInit
method tries to navigate()
to a safe page to prevent utter failure due to an undefined
object's member being accessed within the template.
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
}
}
}
}
Question 1 : Why doesn't the this.router.navigate(['/scenario']);
call work (interrupt the component lifecycle)?
Question 2 : Generically, is there a way to stop the component lifecycle during initialization to permit preemptive navigation to a safe place?
What you want is a guard. Guards can be used to prevent navigation to a route, or you can use them to intercept and redirect like you want in this case. See https://angular.io/guide/router#milestone-5-route-guards
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With