【问题标题】:Cannot read property ‘length’ of undefined in ionic无法读取离子中未定义的属性“长度”
【发布时间】:2018-06-14 22:24:49
【问题描述】:

我不知道为什么会出现此错误。有人可以帮帮我吗。 我已将变量声明为

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

我遇到了类型错误。

错误类型错误:无法读取未定义的属性“长度” FeedsPage.webpackJsonp.260.FeedsPage.addnewcard (feeds.ts:171) 在 FeedsPage.webpackJsonp.260.FeedsPage.ionViewDidLoad (feeds.ts:63) 在 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) 在 t.invoke (polyfills.js:3) 在 r.run (polyfills.js:3) 在 NgZone.run (core.js:4566)

【问题讨论】:

  • 将卡片初始化为空数组cards: Array&lt;any&gt; = []

标签: angular typescript ionic-framework


【解决方案1】:

注意:错误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);
  }
});

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

cards: any[] = [];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 2015-08-10
    • 2020-09-14
    • 2018-01-11
    相关资源
    最近更新 更多