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

Fra*_*ige 2 javascript callback angularjs

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

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

当我在语句this.saved = true中检查'this'对象时,我意识到它指向全局对象,而不是指向Product的实例,因为我有"then.call(this,function(){. .."而不是"然后(这,函数(){..."可以在我的代码中看到.有任何帮助吗?

DRo*_*son 7

使用时then.call(this, function(){});你将then函数调用为this,但这不会影响this你传递的实际回调函数的值.

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

$http.post(url, data).then(function(){
    this.saved = true;
}.bind(this));
Run Code Online (Sandbox Code Playgroud)