I have an Angular application that has CRUD functionalities using localStorage. I need to gather a data object called rubberboot
from a few input fields and push it to a localStorage key rubbberboots
which holds an array of objects.
Stackblitz here: https://stackblitz.com/edit/github-4lgqkx
Using the input fields from lisaa.component.ts the data should be
{ name: "foo", color: "bar", price: 123, availability: 123 }
but instead an empty array is being pushed to localStorage
[[]]
This piece of code in kumpparit.service.ts pushes the rubberboot
to the localStorage:
addRubberboot = (rubberboot: rubberboot) => {
if (typeof (Storage) != undefined) {
let rubberboots = JSON.parse(localStorage.getItem("rubberboots"));
rubberboot.id = this.generateId();
rubberboots.push(rubberboot);
localStorage.setItem("rubberboots", JSON.stringify(rubberboots));
}
}
and this function generates an id
for the rubberboot
object, since the id
comes from localStorage instead of the input fields:
generateId = () => {
if (typeof (Storage) != undefined) {
let rubberboots: rubberboot[] = JSON.parse(localStorage.getItem("rubberboots"));
let index = 0;
for (let rubberboot of rubberboots) {
index++;
}
return index;
}
}
I am expecting the localStorage key rubberboot
to now hold the value of
[ { name: "foo", color: "bar", price: 123, availability: 123, id: 0 } ]
and the next push operation to localStorage would set the value of the rubberboot
key to
[
{ name: "foo", color: "bar", price: 123, availability: 123, id: 0 },
{ name: "foo", color: "bar", price: 123, availability: 123, id: 1 }
]