Reputation: 267049
I want to make a function which fetches some info from an ajax URL. E.g in my service, I would have the following method:
this.getFavColor = function(id)
{
return $http.get('/colors/get/' + id);
}
And in my controller, I would do the following:
$scope.favColor = UserService.getFavColor( id );
The problem however is, $scope.favColor
will be assigned a promise in this case, and the only way to actually change it to the value returned by ajax, is to set a .success()
callback on the promise and use it to update the value.
However, this is quickly becoming cumbersome if I have a lot of things that have to be fetched via ajax. Is there any shortcut, such as may be doing this?
this.getFavColor = function(id, variableToChange)
{
return $http.get('/colors/get/' + id).success(function(jsonResult)
{
variableToChange = jsonResult.favColor;
});
}
And then doing the following in the controller:
UserService.getFavColor( id, $scope.favColor );
Will this method actually work?
Note: I've already considered $resource
but I cannot set up a REST api for my ajax, so please don't suggest it.
Upvotes: 1
Views: 2468
Reputation: 18081
The way $resource does this is by returning an empty object immediatly and then adding data to this object once the response arrives from the server. That's why $resource can only return objects or arrays, not primitives.
ng-bind (and the shorthand {{ }}) actually resolves promises though, so this might be a better solution. I've created a plnkr with three different examples: http://plnkr.co/edit/WOrU5eMOmsgK4wuiSCHu?p=preview
// data.json: {"color":"Blue"}
app.service('UserService',function($http, $q){
return {
// return value can be accessed by {{value.data.color}}
getFavColor: function(id){
return $http.get('data.json');
},
// return value can be accessed by {{value}}
getFavColorWithQ: function(id){
var def = $q.defer();
$http.get('data.json').success(function(data){
def.resolve(data.color);
});
return def.promise;
}
// return value can be accessed by {{value.color}}
,resourceExample: function(id){
var response = {};
$http.get('data.json').success(function(data){
response.color = data.color;
});
return response;
}
}
});
Upvotes: 2