将 'this' 对象传递给 $http 服务的 'then' 回调函数

Passing 'this' object to the 'then' callback function of $http service

我在将 'this' 对象传递给 $http 服务的 'then' 回调函数时遇到问题,如下所示

var Product = function(){
    this.name = "putty";
    this.price = 760;
    $http.post(url, data).then.call(this, function(){
        this.saved = true;
    });
};

当我检查语句 this.saved = true 中的 'this' 对象时,我意识到它指向全局对象而不是预期的 Product 实例,因为我有 "then.call(this, function(){..." 而不是 "then(this, function(){..." ,如我的代码所示。有什么帮助吗???

为此分配一个变量并改用该变量。见下文

var Product = function(){
    var self = this;
    self.name = "putty";
    self.price = 760;
    $http.post(url, data).then(function(response){
        self.saved = true;
    });
};

您需要重新分配:

var Product = function(){
    this.name = "putty";
    this.price = 760,
    self = this;
    $http.post(url, data).then.call(this, function(){
        self.saved = true;
    });
};

当使用 then.call(this, function(){}); 时,您将调用 then 函数作为 this,但这不会影响您所调用的实际回调函数的 this 值通过。

如果你想绑定this到回调,你可以使用bind:

$http.post(url, data).then(function(){
    this.saved = true;
}.bind(this));