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

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();

    });
  }
}

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

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.

Jason
Guest

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