首页 > 解决方案 > 未知的空字符串被添加到 Angular 中的 localStorage

问题描述

我正在使用 localStorage 来保存添加到购物车的项目列表,这是我在展开组件中添加到购物车按钮的功能,

addToCart(item_id){
console.log("clicked: "+item_id);
this.dataTransmit.changeId(item_id);
}

这是收集从不同组件添加到本地存储的所有项目的组件,

ngOnInit(): void {
this.dataTransmit.currentItemId.subscribe(itemID => {

  this.updateStorage(itemID);

});
 //localStorage.clear();
}

updateStorage(itemID) {

let key = JSON.stringify(itemID);
localStorage.setItem(key, JSON.stringify(1));
for (let i = 0; i < localStorage.length; i++){
  let key = localStorage.key(i);
  console.log(key);
}
}

不知何故,我的控制台日志突然检索到一个“”作为键,我意识到当您取消注释localStorage.clear()上面代码中的函数时问题得到解决,但使用它显然不是一个选项,因为我不想清除我的 localStorage每次页面重新加载时,我还为按钮分配了一个 clear() 函数,并确保我的 localStorage 一开始是空的,我做错了什么?

标签: angulartypescriptlocal-storage

解决方案


推荐阅读