How to get angular project with localStorage to work in every browser?

房东的猫 提交于 2020-06-01 06:22:08

问题


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 = [];
}
}

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?


回答1:


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.

See: can i use localStorage.

And: MDN localStorage



来源:https://stackoverflow.com/questions/62048849/how-to-get-angular-project-with-localstorage-to-work-in-every-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!