Search code examples
bookmarksangular-local-storage

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?


Solution

  • 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);
          }
        });
      };
    }