Reputation: 108
I am having problems passing 'this' object to the 'then' callback function of $http service as shown below
var Product = function(){
this.name = "putty";
this.price = 760;
$http.post(url, data).then.call(this, function(){
this.saved = true;
});
};
When I inspect 'this' object in the statement this.saved = true, I realise that it is pointing to the global object and not to an instance of Product as expected since I have "then.call(this, function(){..." instead of "then(this, function(){..." as can be seen in my code. Any help please???
Upvotes: 3
Views: 2092
Reputation: 4471
When using then.call(this, function(){});
you're calling the then
function as this
, but that will not affect the this
value of the actual callback function that you are passing.
If you want to bind this
to the callback, you can use bind
:
$http.post(url, data).then(function(){
this.saved = true;
}.bind(this));
Upvotes: 10
Reputation: 5212
Assign a var to this and use that var instead. See below
var Product = function(){
var self = this;
self.name = "putty";
self.price = 760;
$http.post(url, data).then(function(response){
self.saved = true;
});
};
Upvotes: -1
Reputation: 6620
You need to re-assign it:
var Product = function(){
this.name = "putty";
this.price = 760,
self = this;
$http.post(url, data).then.call(this, function(){
self.saved = true;
});
};
Upvotes: -1