How to localstorage get Data


#1

I have below code in my .ts file

    		this.local = new Storage(LocalStorage);
    		this.local.set('name', name);
    				alert(name);
    	}
    		getData(){
    		this.output=this.local.get('name');
    	}

and in my .html file have below code

    <ion-list>
      <ion-item>
      <ion-label>Input</ion-label>
       <ion-input type="text" [(ngModel)]="name"></ion-input>
      </ion-item>
    </ion-list>

        <button (click)="setData(name)">Set data</button>
    	<button (click)="getData()">Get data</button>
    	
    	<ion-list *ngIf="output">
    	  <ion-item *ngFor="#item of output" >
    		{{item}}
    	  </ion-item>
    	</ion-list>
    {{output}}

When I click on set data, its works fine. But when I click on getData.

it showing [object Object]. What is the method to read get data ?


#2

What I do when saving it to local storage is stringify it.

this.local.set('name', JSON.stringify(name));

And then when getting it back I parse it.

this.output = JSON.parse(this.local.get('name'));

I hope this will solve your problem.


#3

like dtaalbers said: Localstorage is a key-value string-based storage. You can only store strings. You need to convert it back to JSON if you want to work with localstorage values.


#4

Hello Dear,

The Problem you are facing is not about JSON.stringify and all.

Ionic LocalStorage instance.get() return Promise < string > instead of direct data, so you need to use then to obtain your data like belowe code.

constructor() {
  this.local = new LocalStorage("info");
}
setData(name) {
  this.local.set('name', name);
}

getData() {
  this.local.get("name").then((output) => {
      alert(output);
  })
}


 <ion-list>
    <ion-item>
        <ion-label floating>Name</ion-label>
        <ion-input type="text" #txt></ion-input>
    </ion-item>
    <button light (click)="setData(txt.value)">Set</button>
    <button light (click)="getData()">Get</button>
</ion-list>

#5

May be a good idea for you to give a try on localForage, which is capable of storing objects directly if IndexedDB or WebSql are abailble (and fallbacks to localstorage+JSON.stringify when neither are available).

http://mozilla.github.io/localForage/

localForage’s API is asynchronous, as well as Ionic’s Storage’s one; you’ll need to use promises (or callbacks) as well. :slight_smile: