FacundoGFlores FacundoGFlores - 1 month ago 5
TypeScript Question

Angular2 / Typescript - Error pushing element

This is my function:

foo(o) {
let olditems = JSON.parse(localStorage.getItem('key'));
let newitem = {'obj': o};
olditems.push(newitem);
console.log(olditems);
}


I want to push the object
o
to my
localStorage
.

It gives me an error:

error_handler.js:46 EXCEPTION: Error in ... - inline template:7:65 caused by: olditems.push is not a function

Answer

The method .push is not available for objects, if you want to add something to an object you just have to create the property in the object.

olditem.obj = o;

or

olditem['obj'] = o;

And then set the item in you localStorage

Comments