Ionic 2 auth - 如果本地存储上有用户,请跳过登录页面

Ron*_*pes 3 typescript ionic-framework ionic2 ionic3 angular

我有一个Ionic 2应用程序,它在我的Rails 5后端进行身份验证.用户登录后,我将他的信息存储在本地存储中.因此,一旦用户打开应用程序并且他之前已经登录过,就应该跳过登录页面.我试图在app.component设置我的根页面时这取决于是否有关于本地存储上的用户的信息,但该storage.get方法似乎是异步的,所以它在我的检查后执行,所以它总是认为它是假的.

我有什么想法可以解决这个问题?

seb*_*ras 15

您可以在从存储中获取值后设置根页面,如下所示:

@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;
        });
      });
    }

}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,如果用户已经登录,则根页面将是HomePage,如果未登录,则为LoginPage.

  • 这就像一个魅力.我必须读两遍,因为我在rootPage的声明中设置了根页面,导致登录屏幕闪烁几秒钟.很棒的答案! (3认同)