首页 > 解决方案 > 无法读取离子中未定义的属性“长度”

问题描述

我不知道为什么我会收到这个错误。有人可以帮帮我吗。我已将变量声明为

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

这是我的方法

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);
    }
  }

当我按下按钮时,“voteUp”方法被调用

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

我面临类型错误。

错误类型错误:无法在 ViewController._lifecycle ( view-controller.js:486) 在 ViewController._didLoad (view-controller.js:369) 在 NavControllerBase._didLoad (nav-controller-base.js:768) 在 t.invoke (polyfills.js:3) 在 Object. onInvoke (core.js:4749) at t.invoke (polyfills.js:3) at r.run (polyfills.js:3) at NgZone.run (core.js:4566)

标签: angulartypescriptionic-framework

解决方案


注意:错误Cannot read property ‘length’ of undefined通常发生在对 的显式调用时arr.length,我在您的示例中看不到。我可以看到几个我希望看到this.cards is undefined.

您在this.jdetails设置之前循环成员(.then表示异步执行):

this.jobdetail.getJobDetails().then((data) => {
  //console.log(data);
  this.jdetails = data;
});
for (let val of this.jdetails) {
  this.cards.push(val);
}

通过将循环移动到函数中,在数据被检索执行数据处理。.then

this.jobdetail.getJobDetails().then((data) => {
  //console.log(data);
  this.jdetails = data;

  for (let val of this.jdetails) {
    this.cards.push(val);
  }
});

我看不到你的所有代码,因为你没有提供一个独立的例子,但是当你调用push或者pop数组已经初始化时有一个假设。如果你不这样做,你可能会遇到另一个错误。内联或在构造函数中初始化它:

cards: any[] = [];

推荐阅读