javascript - Angular .js :13550 TypeError: Cannot set property 'people' of undefined

标签 javascript angularjs ecmascript-6

我正在学习 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: Cannot set property 'people' of undefined at index.controller.js:22

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

最佳答案

您的范围界定错误。

  • this.src - 本例中的 this 引用您正在构造的 Controller 类。
  • 第 22 行的
  • this.people 引用了它所包含的函数。

我真的不知道 Angular ,但你可能需要做类似的事情:

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

关于javascript - Angular .js :13550 TypeError: Cannot set property 'people' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37482276/

相关文章:

javascript - 在 React-Native 中使用 Navigator 组件自定义导航

html - 如何在 Angularjs 中计算数组值内部的总和?

javascript - es6 javascript推荐使用三元运算符应用模板文字的方法?

javascript - ECMA6 生成器 : yield promise

javascript - 对象数据覆盖所有以前的数据

javascript - 为什么 Angular 加载我的根模板两次

javascript - 在语句中多次修改变量以及 JavaScript 中函数参数的求值顺序

javascript - (Web Audio API) 振荡器节点错误 : cannot call start more than once

javascript - 对使用 $translatePartialLoaderProvider 的 AngularJS 应用程序进行单元测试

javascript - 查找当前数组项的同级