Reputation: 6744
I can't get local storage to work properly. When I do:
this.VEEU_ID = 'veeuID';
this.storage.set(this.VEEU_ID, 11);
alert('Storage was set to: '+JSON.stringify(this.storage.get(this.VEEU_ID)));
I get:
Storage was set to: {"_id":1733,"_state":1,"_result":"11","_subscribers":[]}
I thought that this.storage.get(this.VEEU_ID)
should return the value 11
Upvotes: 3
Views: 15397
Reputation: 5167
Fetching data from Storage is asynchronous which means our application will continue to run while the data loads. A promise allows us to perform some action whenever that data has finished loading, without having to pause the whole application
So an example of that should be:
//set a value in storage
this.storage.set("age", 25);
//get the value from storage
this.storage.get("age").then((value) => {
alert('Storage value: '+ value);
})
More info can be found on the SqlStorage API page
Update for Ionic 2 RC
Since the release of Ionic 2 RC some changes took place:
Storage has been removed from ionic-angular and placed into a separate module, @ionic/storage. Starters have been updated to add this, make sure to add it to your package.json if you’re using the storage system. See more details here.
The following example shows how to Ionic 2 Storage:
First we edit the NgModule
located in src/app/app.module.ts
. The important part is to add Storage
as a provider:
import { Storage } from '@ionic/storage';
@NgModule({
declarations: [
...
],
imports: [
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
...
],
providers: [ Storage ] // Make sure you do that!
})
export class AppModule {}
Now we can inject Storage
into our component:
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, public storage: Storage) {
}
}
After injecting Storage into the component we can use the storage.set
and storage.get
methods:
this.storage.set('name', 'John').then(() => {
console.log('Name has been set');
});
this.storage.get('name').then((name) => {
console.log('Name: ' + name);
});
Upvotes: 10