简体   繁体   English

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

[英]Deleting item from array in localStorage Angular

I have been trying to do this for a while now, the code below is what I currently have and it works when I only have one array in it, but anything over when I run the delete function the whole app freezes and I can't exit out of it can someone tell me what I am doing wrong. 我已经尝试了一段时间了,下面的代码是我当前拥有的代码,当我只有一个数组时它可以工作,但是当我运行删除功能时,一切都结束了,整个应用程序冻结了,我无法退出它可以有人告诉我我在做什么错。 I have auto incormenting ids for each array entered, but I have no clue why it freezes 对于每个输入的数组,我都有自动递增的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>

Rather than storing an array in localstorage, stringify the array while storing and on fetch just parse it. 与其在本地存储中存储数组,不如在存储时对数组进行字符串化,并在提取时仅对其进行解析。 This way you are not storing complicated arrays in the localstorage but a string. 这样,您不是在本地存储中存储复杂的数组,而是在字符串中存储。


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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