我正在编写一个具有保存功能的包装库。基本上它只是调用 $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/