Nav.setRoot won't work from inside a class constructor

Hi!

I’m not really sure if this is a bug or just me doing things the wrong way.

This is the way I’m managing to logout from my app: I created a Logout page and in the constructor I unset some variables and clear local storage and then redirect to Login with this.nav.setRoot(LoginPage). The only problem is that the setRoot is not working properly. From the console I know the Login page is being loaded because I see all events being logged, but the view (the html itself) won’t change to the Login page. Am I doing something wrong?

Thanks!

OMG please at least put the code of the function where the setRoot happens, most likely will be a issue with dependencies or this context.

Didn’t think it was necessary since it is just that simple. A page with a setRoot in the constructor.

import {Page, NavController} from 'ionic/ionic';
import {LoginPage} from '../login/login'

@Page({
  templateUrl: 'build/pages/logout/logout.html'
})
export class LogoutPage {
    
    constructor(nav: NavController) {
        this.nav = nav;
        //random code to unset vars and clear local storage
        this.nav.setRoot(LoginPage);
    }

}

As I said, this somehow executes everything from my LoginPage (I can see from the console) but it doesn’t change the view. If I instead create a method in the class like:

doLogout() {
    this.nav.setRoot(LoginPage);
}

And attach it to a button, it works. But not from the constructor.

If it doesn’t work from the constructor but it does from a function, i think is about timing, like if you use the constructor it breaks because it’s still transitioning the navigation when you try to setRoot, try putting the setRoot statement in a timeout function, again this is merely speculation.

1 Like

Good catch, that was the reason :slight_smile: I ended up putting the code in the onPageDidEnter() http://ionicframework.com/docs/v2/api/components/nav/NavController/

Thank you

Hah, lucky guess, i had to fight a lot with this kind of error with the pre-aplha.47 popups so i had it in my mind.

2 Likes