Voldemort Voldemort -4 years ago 156
Javascript Question

Storage get() never returning value in ionic 2

Learning ionic 2, particularly using

Storage
.

So, I just created a blank app:

ionic start storagetest blank --v2


Following this the docs:

cordova plugin add cordova-sqlite-storage --save
npm install --save @ionic/storage


Then, my
app.module.ts
looks like this:

import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { IonicStorageModule } from '@ionic/storage';

@NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
IonicModule.forRoot(MyApp),
IonicStorageModule.forRoot()
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}


And then went ahead to
home.ts
:

import { Component } from '@angular/core';

import { NavController } from 'ionic-angular';

import { Storage } from '@ionic/storage';

@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {

constructor(public navCtrl: NavController, storage: Storage) {

storage.ready().then(() => {
storage.set('name', 'Max');
storage.get('name').then((val) => {
console.log('Your name is', val);
})
});

}

}


There is nothing in the javascript log. It appears that
get()
is never returning the value. However,
ready()
does work, as I have put a
console.log()
in it.

What is wrong then?

I am running the app on Chrome, Mac OS.

Answer Source

storage.set is asynchronous and returns a promise.So value may not be set when get().then() is called. Try:

 storage.ready().then(() => {
       storage.set('name', 'Max').then(()=>
       storage.get('name').then((val) => {
         console.log('Your name is', val);
       });
      );
     });

You have no error handler in then or catch() method which is probably why nothing is logged.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download