我正在编写一个具有保存函数的包装器库。基本上,它只是调用$http.post
函数并返回promise(为了简洁起见)。
不幸的是,解析promise时调用的函数中的this
运算符(即使用结果数据调用的函数)指向Window
对象。所以我想知道,当promise被解析或拒绝时,是否有一种方法可以将this
运算符绑定到另一个对象?
请查看下面的代码以帮助理解更多内容:
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>
如果您运行上面的代码,则警报显示[Object Window]所以我的问题是:是否可以将this
绑定到SomeService(例如)或其他对象?
附言:一个想法是,也许我可以为$http.get
编写一个包装器,而不是直接返回promise,然后在解析我自己的promise之前以某种方式绑定this
运算符?但我找不到任何关于如何使用(this
)绑定解决承诺的信息。
更新:感谢您的建议我知道关于bind的事,但情况稍微复杂一点SomeService.save方法创建一个Item对象。因此,当promise被解析时,调用SomeService.save()的函数需要创建的项和$http请求返回的数据。我发现我只是将其设置为新的Item Object,并按原样传递$http中的数据。这有道理吗?如果没有,请告诉我,我会创建一个plunkr来解释同样的问题。
这就是bind
方法的作用。
then(function(data) { ... }.bind(window))