javascript - 如何在 AngularJS 中的 $http.post -> 解析/拒绝中绑定(bind) "this"? (现在 this = Window 对象)

标签 javascript angularjs angularjs-scope this

我正在编写一个具有保存功能的包装库。基本上它只是调用 $http.post函数并返回 promise (为了简洁起见)。

不幸的是this在解决 Promise 时调用的函数(即使用结果数据调用的函数)中的运算符指向 Window目的。所以我想知道是否有办法绑定(bind) this运算符到另一个对象,当 promise 被解决或拒绝时?

请查看下面的代码以帮助理解:

angular.module('SomeService', []).service('$service', function($http) {
  this.get = function() {
    return $http.get('http://jsonplaceholder.typicode.com');
  }

  return this;
});

angular.module('testApp', ['SomeService']).controller('testController', function($service) {
  $service.get().then(function(data) {
    alert(this);
    //It should say Object Window!
    //Is is possible to bind `this` to say SomeService (example),
    //Or some other object?

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testApp" ng-controller="testController">
  {{1+1}}
</div>

如果运行上面的代码,警报会显示[对象窗口]。 所以我的问题是:可以绑定(bind) this说 SomeService (示例),或其他一些对象?

附注一个想法是也许我可以为 $http.get 编写一个包装器而不是直接返回 promise ,然后以某种方式绑定(bind) this运营商在解决我自己的 promise 之前?但我找不到任何有关如何使用 ( this ) 绑定(bind)解决 promise 的信息。

更新:感谢您的建议。我了解绑定(bind),但情况有点复杂。SomeService.save 方法创建一个 Item 对象。因此,调用 SomeService.save() 的函数既需要创建的项目,也需要在解决 Promise 时 $http 请求返回的数据。我发现我只需将其设置为新的 Item 对象并按原样传递来自 $http 的数据。这有任何意义吗?如果没有,请告诉我,我将创建一个 plunkr 尝试解释相同的内容。

最佳答案

这就是the bind method是为了。

then(function(data) { ... }.bind(window))

关于javascript - 如何在 AngularJS 中的 $http.post -> 解析/拒绝中绑定(bind) "this"? (现在 this = Window 对象),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37133472/

相关文章:

javascript - 如何在 Reactjs 中禁用按钮 onclick?

javascript - AngularJS 路线

angularjs - 在页面上找不到 Protractor 错误 Angular

javascript - Angularjs 使用 ng-repeat 隔离范围指令

javascript - Angularjs 隔离了没有自己模板的指令范围

AngularJS 将变量添加到作用域问题

javascript - 在 javascript 的正则表达式中传递变量以进行字符串匹配

javascript - 为什么此密码验证码不适用于 jquery 表单向导?

javascript - 如何替换事件页面扩展中的短(不到一分钟)setTimeouts

javascript - 我想使用 angularJs 和 ionic 实现类似于 facebook 的评论部分