【发布时间】:2016-05-10 08:49:04
【问题描述】:
我正在编写一个具有保存功能的包装库。基本上它只是调用$http.post 函数并返回承诺(为简洁起见)。
不幸的是,当 promise 被解析时调用的函数中的 this 运算符(即使用 result 数据调用的函数)指向 Window 对象。所以我想知道当承诺被解决或拒绝时,是否有办法将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 编写一个包装器,而不是直接返回承诺,然后在解决我自己的承诺之前以某种方式绑定this 运算符?但我找不到任何关于如何使用 (this) 绑定解决承诺的信息。
更新:感谢您的建议。我知道绑定,但情况有点复杂。 SomeService.save 方法创建了一个 Item 对象。因此,调用 SomeService.save() 的函数既需要创建的项目,也需要解决 promise 时 $http 请求返回的数据。我发现我只是将它设置为新的项目对象并按原样从 $http 传递数据。这有任何意义吗?如果没有,请告诉我,我会创建一个 plunkr 尝试解释。
【问题讨论】:
-
使用
.then(function() { }.bind(SomeService)) -
也许这会对你有所帮助:what does var that = this mean in javascript
标签: javascript angularjs angularjs-scope this