Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing Ionic 2 root programmatically

I have a project on Android that I would like to change the root page dynamically determined if a user is logged in or not.

In the app.component.ts. I am checking the local storage for a flag that determines if the user is logged in. If they are, it takes them to the 2nd page and doesn't show a login page. If they aren't, it shows them a login page.

My problem is that the local storage GET is a Promise and it finishes up the constructor of app.component.ts before it has an opportunity (it goes to the login screen and shows it) then when the Promise is finished it switches to the 2nd screen. I don't want to show the login screen at all if they are already logged in.

I've tried everything and can't seem to figure this out. How can I change the root page that loads based on the status of a value in the local storage?

like image 391
Sean Avatar asked Nov 22 '16 01:11

Sean


1 Answers

New solution, now a little more ellegant. I only set the root programatically after I reach storage and check whether it should show Home or Login.

@Component({
    template: `<ion-nav #nav></ion-nav>`
)
export class MyApp {

    @ViewChild('nav') nav: Nav;

    constructor(platform: Platform, storage: Storage) {
        this.storage.get('isLogged').then(logged => {
           if (logged) {
              this.nav.setRoot(HomePage);
           } else {
              this.nav.setRoot(LoginPage);
           }
    });
}

Before Edit

Not an ellegant solution, and I will keep around to see if there is a better way, but in my case I postponed the exibition of the root with a *ngIf.

My AppComponent is something like this:

@Component({
   template: `<ion-nav *ngIf="showRoot" [root]="rootPage"></ion-nav>`
})
export class MyApp {

  rootPage:any = LoginPage;

  showRoot = false;

  constructor(platform: Platform, storage: Storage) {

    this.storage.get('isLogged').then(logged => {
        if (logged) {
           this.rootPage = HomePage;
        }
        this.showRoot = true;
    });
  }
}
like image 116
Victor Ivens Avatar answered Nov 09 '22 23:11

Victor Ivens