Skip to content Skip to sidebar Skip to footer

Using Localstorage Ionic 2

I have two text fields and have to take data from both of them and store it using LocalStorage. So here is the code I've implemented but it's not working can you tell me to solve i

Solution 1:

The previous answer is obsolete, here is an UPDATE.

Follow these steps:

  1. Install Storage Module

    $ cordova plugin add cordova-sqlite-storage --save
    $ npm install --save @ionic/storage
    
  2. Add storage into app.module.ts

    import { Storage } from'@ionic/storage';
    
    @NgModule({
    
       ...
    
       providers: [
         Storage
       ]
     })
    export classAppModule {}
    
  3. Use it :)

    import { Storage } from'@ionic/storage';
    
    exportclassMyApp {
        constructor(storage: Storage) {
    
        // set        key   value
        storage.set('myKey', 'myVal');
    
        // get value 
        storage.get('myKey').then((val) => {
          console.log(val);
        })
     }
    }
    

find more on http://ionicframework.com/docs/v2/storage/

Solution 2:

You need to import both Storage and LocalStorage, and you need to add this to your constructor:

this.local = new Storage(LocalStorage);

Docs with and example are here: http://ionicframework.com/docs/storage/

Solution 3:

Actually you need to wait for storage to be ready as well

So as stated before install it

if you intend to use sqlite do this first

$ cordova plugin add cordova-sqlite-storage --save

if not skip it and proceed to do

$ npm install --save @ionic/storage

Next add it to the providers list in your NgModule

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

@NgModule({

 ...

 providers: [
  Storage
 ]
})
export classAppModule {}

Then you can proceed to inject it where needed

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

exportclassMyApp {
constructor(storage: Storage) {

    storage.ready().then(() => {
         // set key   value
         storage.set('myKey', 'myVal');

         // get value 
         storage.get('myKey').then((val) => {
           console.log(val);
         })
    });
  }
}

Post a Comment for "Using Localstorage Ionic 2"