Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic 2 auth - Skip login page if there's an user on local storage

I have an Ionic 2 application that does an authentication on my Rails 5 backend. Once the user is logged, I store his informations on local storage. So, once the user open the apps and he has already logged before, the login page should be skipped. I'm trying to do that on my app.component setting my root page depending on if there's information about the user on local storage or not, but the storage.get method appears to be asynchronous, so it is executing after my check, so it's always considering it false.

Any ideas how I could fix that?

like image 390
Ronan Lopes Avatar asked Dec 04 '22 22:12

Ronan Lopes


1 Answers

You can set the root page after getting the value from the storage like this:

@Component({
    templateUrl: 'app.html'
})
export class MyApp {
    @ViewChild(Nav) navCtrl: Nav;

    public rootPage; // Just declare the property, don't set a value here

    constructor(...) {
      this.platform.ready().then(() => {
        Splashscreen.hide();

        // Get the status from the storage
        this.storage.get('login:status').then(loggedIn => {
          this.rootPage = loggedIn ? HomePage : LoginPage;
        });
      });
    }

}

In this case, if the user is already logged in, the root page will be the HomePage, and if it's not logged in, the LoginPage.

like image 134
sebaferreras Avatar answered Dec 09 '22 15:12

sebaferreras