angular - 未知的空字符串被添加到 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 一开始是空的,我做错了什么?
解决方案
推荐阅读
- angular - 使用 as 关键字,然后在同一 ngIf 中使用长度
- c - GLIBC malloc 实现记账
- c# - WPF - 如何以字符串列表作为内容对 DataGridTemplateColumn 进行排序
- javascript - 脚本不执行输出
- php - 在 Symfony 中显示带有变量的数组
- typescript - 如何使用 rxjs 在 Typescript 中将可观察的两种不同类型的集合转换为不同的第三种可观察类型?
- javascript - 客户端 React JS 发布请求
- javascript - 有没有办法将条件语句从文本变为 if 语句?
- python - Pandas groupby concat 将未分组的列转换为逗号分隔的字符串
- python - 参数必须是字符串或数字 [标签编码]