I'm writing a wrapper library that has a save function. Basically it just calls the $http.post
function and returns the promise (for sake of brevity).
Unfortunately the this
operator in the function that gets called when the promise is resolved (i.e. the function which gets called with the result data) points to the Window
object. So I'm wondering if there is a way to bind the this
operator to another object, when the promise is resolve or rejected?
Please look at the code below to help make more sense:
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>
If you run the code above, the alert says [Object Window]. So my question is: Is possible to bind this
to say SomeService (example), or some other object?
P.S. One idea is maybe I can write a wrapper for $http.get
instead of returning the promise directly and then somehow bind the this
operator before resolving my own promise? But I can't find any info on how to resolve promises with (this
) binding.
Update: Thanks for the suggestions.. I know about bind, but the case is a little more complicated. the SomeService.save method creates an Item object. So the function that calls SomeService.save() needs both the item created and the data returned by the $http request when the promise is resolved. I figured out that I just set this to the new Item Object and pass the data from $http as-is. Does that make any sense? If not, please tell me and I'll create a plunkr trying to explain the same.