Mithun Nath
Mithun Nath

Reputation: 523

How to store and retrieve data using local storage in ionic 2

HTML codes

<ion-item *ngFor="let data of datas">
<ion-button (click)="makefavorite(data)" > Make Favourite </ion-button>
</ion-item>

Typescript codes

makeFavorite(favData){

this.favStorage.set('id',favData.id);
//Storing data test

this.favStorage.get('id').then((val) => {
        console.log('Saved post is', val);
      }); //retrieving data test
 }

The code shows above works just fine. I'm trying to build a list of data that comes from the server through an HTTP call.

This app should let users make lists favorite by clicking the button such as a bookmark or shopping cart.

Data variable is a JSON object contains id, title, content as properties.

Can anyone suggest me on How can I store any lists that user clicks, without overwriting the local storage variable?

Upvotes: 0

Views: 3441

Answers (2)

Kajol Chaudhary
Kajol Chaudhary

Reputation: 267

To set data in local storage:

localstorage.setItem("key","value");

To get data from local storage:

let value = localstorage.getItem("key");

Upvotes: 1

Gavishiddappa Gadagi
Gavishiddappa Gadagi

Reputation: 1180

import { Storage } from '@ionic/storage'

export class MyPage {
itemList: any;
  constructor(public navCtrl: NavController, public storage: Storage) {
    this.storage.get('myList').then((list) => {
      this.itemList = list;
      console.log(list);
    });
  };

  store(val){
    this.storage.get('myList').then((list) => {
      if(list!= null)
      {
        list.push(val);
        this.storage.set('myList', list);
      }
      else
      {
        let list = [];
        list.push(val);
        this.storage.set('myList', list);
      }
    });
  };
}

Upvotes: 2

Related Questions