Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop an Angular 2 component initialization and navigate to a default (safe) route

Tags:

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?

like image 200
Neoheurist Avatar asked Dec 09 '16 13:12

Neoheurist


1 Answers

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

like image 199
Fiddles Avatar answered Oct 01 '22 11:10

Fiddles