Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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 :-)

like image 699
im_bhatman Avatar asked May 18 '26 03:05

im_bhatman


2 Answers

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/

like image 145
Tomas Marik Avatar answered May 20 '26 17:05

Tomas Marik


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/

like image 39
Manu Valdés Avatar answered May 20 '26 17:05

Manu Valdés



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!