Search code examples
javascriptangularjsangular-resource

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


I'm using ES6 with Angular JS 1.X. Whenever I try to access a class-level variable (declared in the constructor) in a $resource.query callback function, I get this error:

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

eg:

Constructor:

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

Class Method:

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

Solution

  • The context of this has changed in the callback function for this.invLookUpSvc.getPortalInvByProdNbrSum().query. To resolve this, you should bind the callback function to the this context:

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