最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Passing 'this' object to the 'then' callback function of $http service - Stack Over

programmeradmin0浏览0评论

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 binding this to then, not to the function that's being passed as an argument to then. 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
Add a ment  | 

3 Answers 3

Reset to default 10

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

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;
    });
};
发布评论

评论列表(0)

  1. 暂无评论