Ionic Storage get doesn't work until reloading page

Viewed 1631

I'm trying to 'get' an Array from the storage, save it to MaschinenArray and generate an ion-list. My only problem with this is, that I have to reload the page after the "ionic serve" command one time, else it says Maschinen = null as an example.

I thought it might be a problem if this function is async and the HTML will be loaded before, but if I trigger the Event later via a button it still says null.

I inititalize the Array above the constructor:

export class MaschinenParkPage {
maschinenArray : Maschine[] = [];

constructor(private menu: MenuController, public alertCtrl: AlertController, public navCtrl: NavController, private storage: Storage) {


    this.storage.get('maschinen').then((buffer) => {

        this.maschinenArray = buffer;
    });

Any ideas? Or is the constructor maybe the wrong spot to initialize some variables?

2 Answers

Do you really need to declare that array?

If you have stored it correctly in the storage you can retrieve a object array as,

export class MaschinenParkPage {
maschinenArray : any;

constructor(private menu: MenuController, public alertCtrl: AlertController, public navCtrl: NavController, private storage: Storage) {


    this.storage.get('maschinen').then((buffer) => {

        this.maschinenArray = buffer;
        console.log(this.maschinenArray);
    });

I have already written something like this in my code already and works perfectly fine. You can go to chrome inspect (press the combination Ctrl+Shift+I) and check console.log

Update: Also go to chrome inspect -> Application tab -> IndexedDB to find 'maschinen' storage. Check it.

Yeah now I remember the problem I guess. I had a similar issue where I wanted to login and and display data according to login details.

  1. First I used location.reload(); that reloads whole app after login which is not nice.

  2. Then I found Events from ionic angular which solved my problem. you can try this. sample code is,

in my sidebar controller where I subscribe it

  this.events.subscribe('user:login', () => {
      this.ngOnInit();
    });

in my login controller

this.storage.ready().then(() => {
      this.storage.set('loginData', response).then(()=>{
        this.events.publish('user:login');
      });
    });

according to my code i retrieve data from storage in ngOnInit. Hope this helps.

Related