user2828442
user2828442

Reputation: 2525

If condition using storage.set is not working in Ionic

Brief Explanation of what is happening: When I open the app on mobile, it directly takes me to dashboard.html from login.html

What I am trying to achieve: When app is opened for the 1st time, after giving username and password, on success response username and password information is saved in local storage. From the next time when app is opened, app goes to login.html, in its ngOnInit() it checks if user is already logged in then it navigates to 'dashboard.htmlelse stays atlogin.html` page.

But it takes me to dashboard.html even at the very first time after app is installed. What am I doing wrong ?

login.ts code:

  ngOnInit()
{

if(this.storage.get('user').then((val) => {
  if(val===''){
    console.log("this key does not exists");
    this.storage.set('user','');
  }
  else {
    this.navCtrl.setRoot(DashboardPage);
    console.log('user::',val);
  }

    console.log("i am out of if");

 }))
 {

 }
{console.log('user',val);});
}

Please check my if condition and let me know what needs to be done.

Upvotes: 0

Views: 381

Answers (1)

Gabriel Barreto
Gabriel Barreto

Reputation: 6421

There's no need for all your storage.get code to be inside of an if statement, it's not even possible (as far as i know, maybe if you return a boolean), you just need this

ngOnInit(){
  this.storage.get('user').then((val) => {
    if (val === '') {
      console.log("this key does not exists");
      this.storage.set('user', '');
    } else {
      this.navCtrl.setRoot(DashboardPage);
      console.log('user::', val);
    }
    console.log("i am out of if");
  });
}

Also you'll need to set your user as '' the first time your app is opened, if you don't do this your val will be null and it'll fall to your else and your user'll gain access to DashboardPage everytime even without beeing logged or having an account at all.

So it would be better if you don't set your user as '', just don't set it and leave it to be null, then you can do as this

ngOnInit(){
  this.storage.get('user').then((val) => {
    if (val) {
      this.navCtrl.setRoot(DashboardPage);
      console.log('user::', val);
    } else {
      console.log("this key does not exists");
    }
    console.log("i am out of if");
  });
}

Hope this helps.

Upvotes: 1

Related Questions