【问题标题】:Angular2 forEach cant read propertyAngular 2 forEach 无法读取属性
【发布时间】:2017-10-10 09:56:33
【问题描述】:

如何在数据forEach() 中调用this.firms

我知道如何在 Angular1 中执行此操作,但在 Angular 2 中的当前项目中不知道。

目前它在 forEach 之外运行良好,但在内部却不行。

 console.log(this.firms[0].name); // works
    var a = 0;
        console.log("--------------");

    data.forEach(function (eachObj) {
      console.log("firms check!");
      console.log(this.firms); // not working
      a = a + eachObj.income; 
      eachObj.name = this.firms[data.firmid - 1].name; // wont work
    });

错误:

Cannot read property 'firms' of undefined

【问题讨论】:

标签: javascript angular angular2-directives


【解决方案1】:

上下文this 未注入forEach() 调用的匿名函数中。这就是 this 未定义的原因。

如果您正在使用 ES6 功能,您可以使用 arrow function,因为它将上下文保留在函数中:

data.forEach(eachObj => {
  console.log("firms check!");
  console.log(this.firms);
  a = a + eachObj.income; 
  eachObj.name = this.firms[data.firmid - 1].name;
});

或者直接绑定上下文:

data.forEach(function (eachObj) {
  console.log("firms check!");
  console.log(this.firms);
  a = a + eachObj.income; 
  eachObj.name = this.firms[data.firmid - 1].name;
}.bind(this));

编辑

正如zeroflagL 所述,您可以简单地将上下文传递给forEach()

data.forEach(function (eachObj) {
  console.log("firms check!");
  console.log(this.firms);
  a = a + eachObj.income; 
  eachObj.name = this.firms[data.firmid - 1].name;
}, this);

【讨论】:

  • 我有同样的问题,我使用的是 Angular 7,但没有一个解决方案有效。
【解决方案2】:

这是 javascript 中范围的基本示例。 在你的函数内部this 指的是函数本身的上下文。外面的世界是无法访问的。

由于您使用带有 Angular 的 Typescript,您可以只使用 arrow function:

data.forEach((eachObj) => {
  console.log("firms check!");
  console.log(this.firms); // not working
  a = a + eachObj.income; 
  eachObj.name = this.firms[data.firmid - 1].name; // wont work
});

这将保留范围,并且您的 this 在其中可用。 在纯 javascript 中,您可以执行以下操作:

var that = this;

data.forEach(function (eachObj) {
  console.log("firms check!");
  console.log(that.firms); // not working
  a = a + eachObj.income; 
  eachObj.name = that.firms[data.firmid - 1].name; // wont work
});

【讨论】:

    【解决方案3】:

    您可以尝试将data 设为数组

    像这样:

    Array.from(data).forEach((eachObj) => {
        console.log("firms check!"); 
        console.log(that.firms);
        eachObj.name = that.firms[data.firmid - 1].name;
    })
    

    这样也行

    【讨论】:

      猜你喜欢
      • 2018-05-13
      • 2018-09-02
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-14
      相关资源
      最近更新 更多