Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting root page in ionic2 and angular2 app based on an asynchronous event

Tags:

angular

ionic2

I'm trying to start a basic ionic2 app and was wondering if my timing of initial app loading is a problem or not. What I'd like to do is set the start page to a login page if the user is not authenticated.

I originally set the rootpage to the home page and then when the async call came back from localstorage, I would then reset the rootpage to the login page if the user was unauthenticated. However, this caused a flickering where they see one page and then get sent to another page.

It seems like what I want to do is wait for the local storage call before I show any screen.

My question is this: as the code stands now, will there be an error condition where the platform ready fires before the root page is set, thus causing some sort of problem? How should I handle this situation in Ionic 2 and Angular 2? Should I make the get localStorage call synchronous, or should I stuff it in another event or method that is part of the app or page lifecycle in Angular 2?

Should I use some sort of observable or await syntax?

export class MyApp {
  rootPage: any;
  local: Storage = new Storage(LocalStorage);

  constructor(platform: Platform) {

    this.local.get('user').then(user => {
      if (user) {
        this.rootPage = TabsPage;
      } else {
        this.rootPage = LoginPage;
      }
    });

    platform.ready().then(() => {
      // Will this ever fire before the rootpage is set?
      StatusBar.styleDefault();

    });
  }
}
like image 588
MonkeyBonkey Avatar asked Apr 16 '16 12:04

MonkeyBonkey


2 Answers

You don't need to add asynchronous call to the local storage as you can see in this example: https://github.com/RedFroggy/ionic2-nfc-app/blob/master/app/app.ts#L52

You just need to check the user existence in the local storage and set the rootPage to the HomePage or LoginPage.

like image 145
Michael Desigaud Avatar answered Nov 01 '22 08:11

Michael Desigaud


You could create dummy initial page (i.e. white background, preloader whatever) to avoid flickering and then switch to login or tabs page.

like image 43
kemsky Avatar answered Nov 01 '22 08:11

kemsky