简体   繁体   中英

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?

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

There is a better way to set the lexical value of this using the new ES6 lambda => syntax. Change your code to use lambda as below and you will get the correct value of 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. So you need to change all you methods to use => to have correct lexical value of this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM