在 $resource.query 回调函数中访问 class 变量时出现 es6 问题

es6 issue while accessing class variables in a $resource.query callback function

我将 ES6 与 Angular JS 1.X 一起使用。每当我尝试在 $resource.query 回调函数中访问 class 级变量(在构造函数中声明)时,我都会收到此错误:

"TypeError: Cannot read property 'maxSize' of undefined".

例如:

构造函数:

constructor() { 
    this.invArr = [];       
    this.maxSize = 3;        
}

Class方法

bindData(){
    this.invArr = this.invLookUpSvc.getPortalInvByProdNbrSum().query({
        rtbProductNbr: this.productNumber
    }, function (data) {
        if (angular.isDefined(data)) {
            this.invArr = data;  //this.invArr not found
            console.log(this.maxSize); //this.MaxSize not found.                 
        }            
     });
}

this 的上下文在 this.invLookUpSvc.getPortalInvByProdNbrSum().query 的回调函数中发生了变化。要解决此问题,您应该将回调函数绑定到 this 上下文:

bindData(){
    this.invArr = this.invLookUpSvc.getPortalInvByProdNbrSum().query({
        rtbProductNbr: this.productNumber
    }, function (data) {
        if (angular.isDefined(data)) {
            this.invArr = data;
            console.log(this.maxSize);                
        }            
     }.bind(this));
}