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

标签 javascript angularjs callback

我在将“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(){..."。有什么帮助吗???

最佳答案

当使用 then.call(this, function(){}); 时,您正在调用 then 函数作为 this,但是这不会影响您传递的实际回调函数的 this 值。

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

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

关于javascript - 将 'this'对象传递给$http服务的 'then'回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30268550/

相关文章:

javascript - 滚动到 Li Javascript

javascript - 运行多个模式时出错

javascript - 如何从子文件夹页面(图像输出)重定向主页(索引)

javascript - AngularJS 花括号没有解析,但 ng-bind 有效

javascript - 按日期过滤 Angular 排序

javascript - 我可以在 jquery 中使用带有 .submit 的回调吗

javascript - 无法解析模块 expo-constants

javascript - 缩小JS文件后 Angular 控制不起作用?

javascript - 如何等待一个 jquery 动画在下一个动画开始之前完成?

javascript - Google reCAPTCHA 数据回调不起作用