如何在每个浏览器中使用localStorage获取有角度的项目?

问题描述 投票:0回答:1

我正在一个具有购物车列表组件的电子商务网站上,我使用localStorage如下实现了它,

 export class CheckOutHomePageComponent implements OnInit {

currentArr:string;
myCart:string[] = [];
prices:any;
constructor(
private dataTransmit: DataTransmitService,
private itemsService: ItemsService,
) { }

ngOnInit(): void {
this.dataTransmit.currentItemId.subscribe(itemID => {
  this.myCart = [];
  this.myCart = this.addToCart(itemID);
  for(let i of this.myCart){
    console.log("myCart : "+i);
  }
});
}

addToCart(itemID){
let isAdded = false;
let itemIdStr: string;
let currentArrA:string[] = [];
this.currentArr = localStorage.getItem('currentArray');
itemIdStr = itemID.toString();
currentArrA = this.currentArr.split(",");
for(let i of currentArrA){
  if(i===itemIdStr){
    isAdded = true
  }
}
if(!isAdded){
  localStorage.setItem("currentArray", this.currentArr+","+itemIdStr);
}
this.currentArr = localStorage.getItem('currentArray');
// console.log(this.currentArr);
currentArrA = this.currentArr.split(",");
return currentArrA;
}

clearList(){
localStorage.setItem("currentArray","");
console.log("cleared..."+localStorage.getItem('currentArray'));
this.myCart = [];
}
}

这在我的chrome浏览器上工作正常,并且控制台显示myCart数组的日志,我将其发送给我的朋友,并且在两个浏览器中都不适用于他,我在firefox上尝试了它,但对我却不起作用同样,我猜想localStorage函数需要浏览器的某种授权吗?我该如何解决这个问题?

angular typescript browser local-storage angular9
1个回答
1
投票

localStorage只能处理字符串键/值对。

localStorage.setItem('currentArray', JSON.stringify(this.currentArr));
// and:
const o = localStorage.getItem('currentArray');
if (o) {
   this.currentArr = JSON.parse(o);
}

不需要额外的身份验证。

© www.soinside.com 2019 - 2024. All rights reserved.