【问题标题】:angular.js:13550 TypeError: Cannot set property 'people' of undefinedangular.js:13550 TypeError:无法设置未定义的属性“人”
【发布时间】:2016-05-27 11:26:05
【问题描述】:

我正在学习 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

this.src可以设置成功,为什么this.people不能设置?

【问题讨论】:

    标签: javascript angularjs ecmascript-6


    【解决方案1】:

    你的范围是错误的。

    • this.src - 在这种情况下,this 引用了您正在构建的控制器类。
    • 第 22 行的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 - 
        });
    }
    

    【讨论】:

    • 谢谢!我没有考虑上下文
    【解决方案2】:

    有一种更好的方法可以使用新的 ES6 lambda => 语法来设置 this 的词法值。如下更改您的代码以使用 lambda,您将获得正确的 this 值:

    getPeopleList = () => {
        return this._TestSecService.getPeopleList().then(function(res){
            this.people = res.data; //line: 22
        });
    }
    

    this 的值在 constructor 中的词法设置是正确的,但在类的其他方法中却没有。因此,您需要更改所有方法以使用 => 以获得正确的 this 词法值

    【讨论】:

    • 感谢您的回答
    猜你喜欢
    • 2016-09-22
    • 2016-09-20
    • 2015-09-09
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多