2017-05-11 83 views
11

如何在數據forEach()內撥打this.firmsAngular2 for each cant read property

我知道如何在Angular1做到這一點,但不與角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 
+0

請爲我們提供一個https://plnkr.co/edit/ – SjaakvBrabant

+1

[將範圍傳遞給forEach]的可能重複(http://stackoverflow.com/questions/ 19733758 /傳遞範圍到foreach) – Erazihel

回答

18

上下文this不是由forEach()叫做匿名函數注入。這就是爲什麼this未定義。

您可以使用arrow function如果你使用ES6的特性,因爲它使在功能上下文:

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); 
+0

這是否會異步? –

1

這對在JavaScript範圍基本的例子。 函數內部this引用函數本身的上下文。外部世界不可訪問。

由於您使用的打字稿與角度,你可以只使用一個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 
}); 
2

你可以試着讓data是和數組

像這樣:

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

這將工作以及