如何使用localStorage获取Angular项目以在每个浏览器中工作? [英] How to get angular project with localStorage to work in every browser?
问题描述
我正在一个具有购物车列表组件的电子商务网站上,我使用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数组的日志,我将其发送给我的朋友,并且在两个浏览器中均不适用于他.我也是,我猜测函数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);
}
不需要额外的身份验证.
There is no need for extra authentication.
请参阅:我可以使用localStorage .
并且: MDN localStorage
这篇关于如何使用localStorage获取Angular项目以在每个浏览器中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!