2016-05-27 12 views
2

私は+ +6のコードを学習しています。angular.js:13550 TypeError: 'people'が未定義のプロパティ 'people'を設定できません

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) 

これを行う場合は、エラーがあります。なぜthis.peopleができない

angular.js:13550 TypeError: Cannot set property 'people' of undefined at index.controller.js:22

this.srcは、正常に設定できますか?

答えて

2

スコープが間違っています。

  • this.src - この場合thisは構築コントローラクラスのyoureを参照します。
  • this.people on line 22は、その中に含まれる関数を参照します。

私は本当に、角度知らないけど好きには何かをする必要があるかもしれません:新しいES6ラムダ=>構文を使用して、このの字句値を設定するためのより良い方法はあり

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

ありがとう!私は文脈について考えなかった – mqliutie

0

。以下のようにラムダを使用するようにコードを変更し、あなたがthisの正しい値を取得します:

thisの値が字句クラスの他のメソッドでは正しく constructor内ではなく、設定されている
getPeopleList =() => { 
    return this._TestSecService.getPeopleList().then(function(res){ 
     this.people = res.data; //line: 22 
    }); 
} 

。だからあなたはすべて=>の正しい字句の値を使用する方法を変更する必要があります

+0

あなたの答えをありがとう – mqliutie

関連する問題