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));
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…