Search code examples
angularangular2-routing

App Component Not Called When Routing from Login Page to Dashboard


I have a login Component on Successful authentication

in login.component.ts login() { this.loading = true; this.authenticationService.login(this.model.username, this.model.password) .subscribe( data => { this.router.navigate([this.returnUrl]); }, error => { this.alertService.error(error); this.loading = false; }); }

I save UserObject in LocalStorage and then

i redirect to Dashboard Page using

this.router.navigate

In My App.component.ts i check if UserObject is in LocalStorage

constructor(private router: Router) { if (localStorage.getItem('currentUser')) { this.userLoggedIn = true; const user = JSON.parse(localStorage.getItem('currentUser')); this.userObject = user['return_object']; } }

I use userLoggedIn variable in app.component.html to conditionally show header and left navigation but for some reason the code in App.component.ts doesnt executes can someone point me to the right direction.


Solution

  • can you please write you code like this,

    constructor(router:Router) {
      router.events.subscribe(event:Event => {
        if(event instanceof NavigationStart) {
             //you code for checking and navigation
        }
      });
    }
    

    suggestion is to subscribe route event and do action based on it , because constructor get executed once only when component get created till get destroyed.