角度.js:13550 类型错误: 无法设置未定义的属性'people'



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

如果这样做,则会出现错误:

角度.js:13550 类型错误:无法设置未定义的属性"人" at index.controller.js:22

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

你的范围是错误的。

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

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

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

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

最新更新