[英]angular.js:13550 TypeError: Cannot set property 'people' of undefined
I am learning angular+ES6 to code.我正在学习 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)
If do this, there has an error :如果这样做,则会出现错误:
angular.js:13550 TypeError: Cannot set property 'people' of undefined at index.controller.js:22 angular.js:13550 TypeError: 无法在 index.controller.js:22 处设置未定义的属性“people”
this.src
can set successfully,why this.people
can not? this.src
可以设置成功,为什么this.people
不能?
your scoping is wrong.你的范围是错误的。
this.src
- the this
in this case references the controller class youre constructing. this.src
-在this
在这种情况下引用控制器类的youre建设。this.people
on line 22 references the function it is contained within.第 22 行的this.people
引用了它所包含的函数。I dont know angular really but you might need to do something like :我真的不知道角度,但你可能需要做一些类似的事情:
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 -
});
}
There is a better way to set the lexical value of this using the new ES6 lambda =>
syntax.有一种更好的方法可以使用新的 ES6 lambda =>
语法来设置 this 的词法值。 Change your code to use lambda as below and you will get the correct value of this
:更改代码中使用lambda作为下面,你会得到的正确值this
:
getPeopleList = () => {
return this._TestSecService.getPeopleList().then(function(res){
this.people = res.data; //line: 22
});
}
The value of this
is lexically set correctly within the constructor
but not in other methods on the class. this
的值在constructor
词法设置正确,但在类的其他方法中未正确设置。 So you need to change all you methods to use =>
to have correct lexical value of this所以你需要改变你所有的方法来使用=>
以获得正确的词法值 this
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.