How to retrieve the value from LocalStorage

限于喜欢 提交于 2019-11-29 15:32:48

If you are trying to store arrays or objects in localStorage, you will need to convert it into a string format, as localStorage only supports the storing of string values. You can use JSON.stringify() for that purpose.

localStorage.setItem('Values', JSON.stringify(this.newItem));

localStorage.setItem('dataSource', JSON.stringify(this.items));

Likewise, when you need to retrieve the item from localStorage, you can use JSON.parse() to convert it back into an array or object.

const storedItems = JSON.parse(localStorage.getItem('dataSource'));

On your constructor, you are overcomplicating the way you populate your array. After populating the myItems array, you can store it in your localStorage.

On your addItem() method, you can simply push the new items to your myItems array, and call localStorage.setItem(), which will overwrite the previous value stored on your Values key.

myItems: string[] = [];

constructor(){
  console.log(JSON.parse(localStorage.getItem('Values')));

  this.myItems.push('First Value', 'First Value', 'Third Value', 'Forth Value', 'Fifth Value');
  localStorage.setItem('Values', JSON.stringify(this.myItems));
}

addItem() {
  const newItem = ''; //replace that with any value you desire
  this.myItems.push(newItem)
  localStorage.setItem('Values', JSON.stringify(this.myItems));
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!