如何使用 localStorage 获得 Angular 项目以在每个浏览器中工作? [英] How to get angular project with localStorage to work in every browser?

查看:25
本文介绍了如何使用 localStorage 获得 Angular 项目以在每个浏览器中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working on a e-com site which has a cart list component, I implemented it using localStorage as follows,

 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 需要浏览器的某种授权?我该如何解决这个问题?

This works fine on my chrome browser and the console displays the log of myCart array, I sent it to my friend and it doesn't work for him in both browsers, I tried it with firefox and it didn't work for me as well, I'm guessing the function localStorage needs some sort of authorization from the browser? how do I solve this issue?

推荐答案

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

localStorage can handle only string key/value pairs.

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

无需额外的身份验证.

请参阅:我可以使用 localStorage 吗.

以及:MDN localStorage

这篇关于如何使用 localStorage 获得 Angular 项目以在每个浏览器中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆