简体   繁体   中英

Delete array from ionic2 local storage

my data gets stored in an string

i use JSON.parse to convert data to arrays

this.items = JSON.parse(todos); 

I have a results page which prints out my arrays: Array1 Array2 Array3

I have a delete button after every array which deletes the item from the list but not from local storage. Am I doing something wrong?

list.html

<ion-item-sliding *ngFor="let item of items">
  <ion-item>
  <p>{{item.amount}}tk X {{item.class}} / {{item.size}}ml / {{item.proof}}%</p>
  </ion-item>
  <ion-item-options>
  <button danger (click)="removePost(item)">
  <ion-icon name="trash"></ion-icon>Remove
  </button>
  </ion-item-options>
  </ion-item-sliding>

list.ts

removePost(item){
    let index = this.items.indexOf(item);
   if(index > -1){
      this.items.splice(index, 1); // works
      this.storage.remove(this.items[index]); // doesn't work
    }
}

if you have a JSON array in the local storage as a string and if you want to remove an object from local storage array then this will not work.

you can't remove an object because the whole value of localstorage is a string value. what you can do is after removing the value using splice you can set the localstorage again

removePost(item){
   let index = this.items.indexOf(item);
   if(index > -1){
      this.items.splice(index, 1); // works
      //this.storage.remove(this.items[index]); // doesn't work
      localStorage.setitem("name_of_the_storage",JSON.stringify(this.items))
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM