Cannot read property 'length' of undefined


#1

I don’t know why I’m getting this error. Can someone please help me.
I’ve declared variables as

jdetails: Array<any>;
cards: Array<any>;

This is my method

ionViewDidLoad() {
    console.log('ionViewDidLoad FeedsPage');
    //for new card
    this.addnewcard();
    console.log(this.cards);
  }
addnewcard() {
    this.jobdetail.getJobDetails().then((data) => {
      //console.log(data);
      this.jdetails = data;
    });
    for (let val of this.jdetails) {
      this.cards.push(val);
    }
  }

When I press button,“voteUp” method get invoked

voteUp() {
    let removedcard = this.cards.pop();
    this.addnewcard();
  }

I’m facing type error.

ERROR TypeError: Cannot read property ‘length’ of undefined
at FeedsPage.webpackJsonp.260.FeedsPage.addnewcard (feeds.ts:171)
at FeedsPage.webpackJsonp.260.FeedsPage.ionViewDidLoad (feeds.ts:63)
at ViewController._lifecycle (view-controller.js:486)
at ViewController._didLoad (view-controller.js:369)
at NavControllerBase._didLoad (nav-controller-base.js:768)
at t.invoke (polyfills.js:3)
at Object.onInvoke (core.js:4749)
at t.invoke (polyfills.js:3)
at r.run (polyfills.js:3)
at NgZone.run (core.js:4566)

<div swing-stack #myswing1 [stackConfig]="stackConfig" (throwoutleft)="voteDown()" (throwoutright)="voteUp()" id="card-stack" >
		<ion-card #mycards1 swing-card *ngFor="let card of cards">
   //code
<ion-card>
<div>

#2

have you use addnewcard.length in your html or ts file ?


#3

no I’ve not decleared it.


#4

You have not defined cards, at least not in any of the code you posted. What’s being logged to the console here: console.log(this.cards);?

Also there’s no way to know what this does this.jobdetail.getJobDetails() because you didn’t post what that was. And you almost certainly have an async error in addnewcard.


#5

So declaring type of variable does not mean you actually initialized that variable as an Array (in this case). You should initialize it in constructor or in a proper lifecyclehook:

this.cards = [];