mqliutie mqliutie - 6 months ago 64
AngularJS Question

angular.js:13550 TypeError: Cannot set property 'people' of undefined

I am learning angular+ES6 to code.

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


this.src
can set successfully,why
this.people
can not?

Answer

your scoping is wrong.

  • this.src - the this in this case references the controller class youre constructing.
  • this.people on line 22 references the function it is contained within.

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