Using this.storage.get in the constructor

Hello,
right now I am trying to use a variable I am getting from my storage in the constructor of one of my pages. When I try to acces this variable in the constructor ( as in console.log("Number: ", number); ) it returns null.
What am I doing wrong?
This is my constructor:

constructor(public navCtrl: NavController, private storage: Storage, public navParams: NavParams) {
    let number;
    this.storage.get('group').then((val) => {
      number = val;
    });
    storage.ready().then(() => {
      console.log("Number: ", number);
    });
  }
this.storage.ready().then(() => {
   this.storage.get('group').then((val) => {
      number = val;
      console.log("Number: ", number);
   });
});

you just want to do this ?

No I want to do more than that, I just simplified my problem.
I am mostly wondering why I can not access the number variable in my constructor.

I would highly recommend not interacting directly with Storage from pages, but instead moving that into a service provider. I would also recommend not relying on Storage for in-app communication, if that’s what’s going on. Finally, to answer your question, first you must wait on ready() as @kocei pointed out, but since storage operates asynchronously, the only place you can rely on the value is inside a then clause off the get call.

1 Like