using LocalStorage ionic 2

2019-07-20 10:18发布

问题:

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 it.

in page1.html

<ion-input [(ngModel)]="hour" type="number"  ></ion-input>

 <ion-input [(ngModel)]="min" type="number" ></ion-input>

<button clear (click)="setTime(hours.value,min.value)" item-right >settime</button>

in pag1.ts

export class Page1 {

   public hour;
   public min;
   public local:Storage; 

  constructor(public nav: NavController, translate:TranslateService) {}


 setTime(hour, min){

   if(hour<24 && hour>0 && min>0 && min<61){
       this.local.set('hour',JSON.stringify(hour));
       this.local.set('min',JSON.stringify(min));
   }
   else{
     console.log("OUTOF LIMIT TIME EXCEPTION the values are "+hour+min);
   }
 }

  }

on console log, it is showing [Object Object] at the end

and please also tell about get from localStorage. Thanks in advance :-)

回答1:

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/



回答2:

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 class AppModule {}
    
  3. Use it :)

    import { Storage } from '@ionic/storage';
    
    export class MyApp {
        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/



回答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 class AppModule {}

Then you can proceed to inject it where needed

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

export class MyApp {
constructor(storage: Storage) {

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

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