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???
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???
Share Improve this question asked May 15, 2015 at 20:53 Francis EzengigeFrancis Ezengige 1087 bronze badges 2-
2
Your problem is that
.call
is bindingthis
tothen
, not to the function that's being passed as an argument tothen
. What would work is.then(function(){ this.saved = true; }.bind(this);
– DRobinson Commented May 15, 2015 at 20:59 - @DRobinson Possibly make that an answer? – Kevin B Commented May 15, 2015 at 21:05
3 Answers
Reset to default 10When 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));
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;
});
};
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;
});
};