Error when pushing string to Array <string>


#1

Hello,

I’m trying to add a string to an Array <string> whenever the user clicks on a button, here’s the HTML:


<button ion-button clear small color="primary" (click)="saveItem()" icon-left>
    <ion-icon name='bookmark'></ion-icon>
</button>

-----

public saved_feeds: Array <string>;

saveItem () {
  this.number = this.saved_feeds.push ("test");
}

This method is currently just a test, what I really need to do is:


<button ion-button clear small color="primary" (click)="saveItem(feed.ID)" icon-left>
    <ion-icon name='bookmark'></ion-icon>
</button>

----

public saved_feeds: Array <string>;

saveItem (id) {
  this.number = this.saved_feeds.push ("teste");
}

this feed id comes froms another Array:

public feeds: Array <any>;
<ion-card *ngFor="let feed of feeds">

Whenever I click on saveItem, I’m getting this error:

undefined is not an object (evaluating 'this.saved_feeds.push')

How can I append ID from feed.ID to public saved_feeds: Array <string>;?

Thank yoU!


#2

Your Array Is Not Initialized.
Change This In Your .ts File

public feeds: Array = [];


#3

Hey there, I’m using feeds without initializing, why do I have to initialize saved_feeds?

BTW, that indeed solved my problem, thank you!


#4

Without initialize array doesn’t exist in memory that’s why it’s returning undefined
and you can’t push the data without initialize array


#5

You shouldn’t be. Always initialize all arrays and objects. Also, give feeds a proper type. Stop abusing any.