【问题标题】:Delete array from ionic2 local storage从 ionic2 本地存储中删除数组
【发布时间】:2017-11-07 20:07:12
【问题描述】:

我的数据被存储在一个字符串中

我使用 JSON.parse 将数据转换为数组

this.items = JSON.parse(todos); 

我有一个打印出我的数组的结果页面: 阵列1 数组2 数组3

我在每个数组后面都有一个删除按钮,它从列表中删除项目,但不是从本地存储中删除。我做错了吗?

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
    }
}

【问题讨论】:

  • 您如何将数据存储在本地存储中?本地存储不带数组或对象,只带字符串。
  • this.items = JSON.parse(todos);
  • this.items[index] 这是一个对象吧?
  • 你可以分享存储项目的截图吗?

标签: arrays angular typescript ionic2 storage


【解决方案1】:

如果你在本地存储中有一个 JSON 数组作为字符串,并且你想从本地存储数组中删除一个对象,那么这将不起作用。

您不能删除对象,因为 localstorage 的整个值是一个字符串值。您可以做的是在使用 splice 删除值后,您可以再次设置本地存储

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

【讨论】:

    猜你喜欢
    • 2016-12-09
    • 2013-04-16
    • 2017-08-07
    • 1970-01-01
    • 2018-01-25
    • 2019-05-16
    • 2018-10-12
    • 2013-01-29
    • 2019-11-26
    相关资源
    最近更新 更多