从localStorage Angular中的数组中删除项目

时间:2019-08-13 16:06:00

标签: javascript angular

我已经尝试了一段时间了,下面的代码是我当前拥有的,当我只有一个数组时,它可以工作,但是当我运行删除功能时,一切都结束了,整个应用程序冻结了,无法退出,有人可以告诉我我做错了什么。输入的每个数组都有自动递增的ID,但是我不知道为什么冻结

/*Favourites Service */
public deleteLocalStorage(id, i ): void {
  const currentArray = this.storage.get(this.STORAGE_KEY);
  for (i = 0; i < currentArray.length;) {
    if (currentArray[i].id === id) { currentArray.splice(i, 1); }
  }
  // insert updated array to local storage
  this.storage.set(this.STORAGE_KEY, currentArray);
}
/*Home page Delete function*/
deleteFav(id, i) {
  this.Local.deleteLocalStorage(id, i);
  console.log(id, i);
}
<div class="panel col-5" (click)="deleteFav(stop.id, i)">
 <img class="panel-remove" src="assets/img/icon_remove.png" />
</div>

1 个答案:

答案 0 :(得分:2)

与其在本地存储中存储数组,不如在存储时对数组进行字符串化,并在提取时对其进行解析。这样,您就不会在本地存储中存储复杂的数组,而是在字符串中存储


public deleteLocalStorage(id, i ): void {
  const currentArray = JSON.parse(this.storage.get(this.STORAGE_KEY));
  for (i = 0; i < currentArray.length; ++i) {
    if (currentArray[i].id === id) { currentArray.splice(i, 1); }
  }
  // insert updated array to local storage
  this.storage.set(this.STORAGE_KEY, JSON.stringify(currentArray));
}


localStorage.set(key, JSON.stringify(arr));

let x = JSON.parse(localStorage.get(key));
相关问题