Lloyd Banks Lloyd Banks - 6 months ago 12
AngularJS Question

Updating 'this' Context Property Inside of a $Promise In An Angular JS Service

I have a function being used in my service that is defined as:

var getData = function() {
return anotherService.getData().$promise;
};


and a
this
property that I manipulate throughout the service.

this.someProperty = 'a string';


I call the above function inside the return section of my service:

return{
updateProperty: function(){
getData().then(function(data){
this.someProperty = data;
});
}
}


In the above, I get an
this is undefined
related error in my browser console. I assume this is because the resolved
$promise
is an AJAX call and
this
is used out of context. What's the best way to manipulate a
this
property using the returned data from an AJAX call in this instance?

Answer

if you're manipulating this throughout your service, assign it to a variable like var self = this. The problem is that this is the context of a function and can be changed by other code using fn.call(context) or fn.apply(context, args). So it's liable to be different inside of the scope of any given function.

So just assign it to some variable and use it:

var self = this;

return {
    updateProperty: function(){
        getData().then(function(data){
            self.someProperty = data;
        });
    }
};