如何绑定“;这个“;在$http.post中->在AngularJS中解析/拒绝?(现在this=Window对象
How to bind "this" in $http.post -> resolve / reject in AngularJS? (right now this = Window object)
我正在编写一个具有保存函数的包装器库。基本上,它只是调用$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))
相关文章:
- $(this).prop('property') vs. this.property
- Twitter Bootstrap typeahead:使用“this”获取上下文/调用元素
- 在流星上使用微信js-sdk时出现拒绝权限错误
- 在另一个函数中使用变量this
- this.router在AngularJS 2中未定义
- reactjs this.refs vs document.getElementById
- JavaScript 中的嵌套函数和 “this” 关键字
- 在Nodejs中Express输入DEBUG=app时权限被拒绝/bin
- React+Meteor:this.ops返回未定义
- javascript中对象构造函数中的var属性与this.properties
- 函数中this和var之间的区别
- jQuery(this).Pparent().Pparente().Prent().find()在iPad上不起作用
- 简单的ES6承诺问题-交换解决和拒绝参数
- javascript第三个XMLHttpRequest被拒绝.但前两个是允许的
- Understanding Javascript scope with "var that = this&qu
- 在ES6 Promise中,我应该在解决/拒绝之前使用return吗
- 定义this.properties或objectName.properties的javascript JSON对象
- Object.prototype using 'this'
- 在JavaScript类型的函数中避免self-this
- 如何绑定“;这个“;在$http.post中->在AngularJS中解析/拒绝?(现在this=Window对象