[英]angular.js:13550 TypeError: Cannot read property 'compile' of undefined?
[英]angular.js:13550 TypeError: Cannot set property 'people' of undefined
我正在學習 angular+ES6 編碼。
test.controller.js
class TestSecIndexController {
constructor (TestSecService,$q) {
this.src = require('./../images/2.jpg');
this._TestSecService = TestSecService;
let promises = [
this.getPeopleList()
];
$q.all(promises).then(function (){
console.log(this.people);
})
}
getPeopleList(){
return this._TestSecService.getPeopleList().then(function(res){
this.people = res.data; //line: 22
});
}
static testSecIndexController(TestSecService,$q){
return new TestSecIndexController(TestSecService,$q);
}
}
TestSecIndexController.testSecIndexController.$inject = ['TestSecService','$q'];
export default angular.module ('test2.index.controller', [])
.controller ('testSecIndexController', TestSecIndexController.testSecIndexController)
如果這樣做,則會出現錯誤:
angular.js:13550 TypeError: 無法在 index.controller.js:22 處設置未定義的屬性“people”
this.src
可以設置成功,為什么this.people
不能?
你的范圍是錯誤的。
this.src
-在this
在這種情況下引用控制器類的youre建設。this.people
引用了它所包含的函數。我真的不知道角度,但你可能需要做一些類似的事情:
let promises = [
this.getPeopleList()
];
let people = null;
getPeopleList(){
let _this = this; //set _this equal to the parent scope
return this._TestSecService.getPeopleList().then(function(res){
//now _this.people refers to the already defined people of the constructor above
_this.people = res.data; //line: 22 -
});
}
有一種更好的方法可以使用新的 ES6 lambda =>
語法來設置 this 的詞法值。 更改代碼中使用lambda作為下面,你會得到的正確值this
:
getPeopleList = () => {
return this._TestSecService.getPeopleList().then(function(res){
this.people = res.data; //line: 22
});
}
this
的值在constructor
詞法設置正確,但在類的其他方法中未正確設置。 所以你需要改變你所有的方法來使用=>
以獲得正確的詞法值 this
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.