Push is not a function angular

I get the error

this.items.push is not a function

From googling I’ve found out that this means that items is not an array. I’ve tried to account for this by checking if it’s undefined and using this.items = this.items || ; I also tried to change data and make it an array but when I enclose data in square brackets, nothing gets pushed to items.

It’s very hard to troubleshoot because the error only shows up in the developer console after I’ve deployed it. No errors show up in the developer console when I am in development mode.

items = [];
storageKey = 'MyDataStorageKey';

public onSubmit(thumbnail, quantity, product_name, product_price){

var data = {
   thumbnail,
   quantity,
   product_name,
   product_price
};

this.items = this.items || [];
if (typeof this.items !== 'undefined')
this.items.push(data);
localStorage.setItem(this.storageKey, JSON.stringify(this.items));
this.isSubmitted = true;
}
ngOnInit(): void {
   this.items = this.getStorageItems();
 }

I also get the error: Cannot find a differ supporting object ‘[object Object]’ of type ‘object’. NgFor only supports binding to Iterables such as Arrays. I get the error for the following:

<tr *ngFor="let item of items">
<td>
<td><img src="../assets/images/gallery/{{item.thumbnail}}" /></td>
<td>{{item.quantity}} </td>
<td>{{item.product_name }}</td>
<td>{{item.product_price }} </td>
</tr>

What do you get console logging this.items?

this.items = this.items || [];

wont return [ ] if this.items is something (for example, an object, and you’d get exactly that error)

When I run console.log(this.items); in development mode, it shows that it’s an array but when I run it in production mode, it’s an object.

I googled “convert object to an array” and tried everything but nothing worked.

I noticed that you’re using the browser local storage. Make sure that you have purged your browser’s storage since the last time you made any changes to this component. If it’s not just an old data issue, the most likely culprit is your getStorageItems function.

It seems like when you’re on production mode the items become object due to the one-liner you have this.items = this.items || [];

Try to change this and acheive the same thing another way and then re-check if you get the same error.

The issue comes when javascript thinks you’re assigning an object to your array and not adding an object to you array. (Also when trying to have consistent data always try … to clone them)

Good luck :call_me_hand:

Thanks but this issue was fixed by adding the following to the html:
<div *ngIf="items.length > 0;">

1 Like