You do indeed need to return a promise, which is exactly how promises are
designed to be used!
app.controller("MyController", ["$scope","myService",
function($scope, myService){
$scope.modelObjs = new Array();
myService.getStuff().then(function(stuff) {
$scope.modelObjs.push(stuff);
});
});
app.factory(['$http', function($http) {
var service = {
url: "https://someurl.com/someWebService.php?someParam=whatever";
getStuff: function() {
// Get model data from web service
return $http.jsonp(service.url).then(function(response) {
// Massage model data from service into exact form we want
return {
someAttr: response.data[i].whatever,
...
};
};
}
};
return service;
});
On 19 June 2015 at 15:10, Scott Knick <[email protected]> wrote:
> I'm currently attempting to pull some $http.jsonp() calls and promise
> follow-on code out of my controller so it can be reused as a service by
> multiple controllers. However, trying to understand how to implement this
> is killing me. Consider that I have something like this for a controller:
>
> app.controller("MyController", ["$scope","$http",
> function($scope, $http){
> $scope.modelObjs = new Array();
>
> // Get model data from web service
> $http.jsonp("https://someurl.com/someWebService.php?someParam=whatever
> ").then(
> function(response)
> {
> // Massage model data from service into exact form we want
> var thisObj =
> {
> someAttr: response.data[i].whatever,
> ...
> };
>
> $scope.modelObjs.push(thisObj);
> });
> });
>
> Getting the jsonp call and resultant promise code out and into a service
> is what I want so it would look something like this in the controller:
>
> app.controller("MyController", ["$scope","$http",
> function($scope, $http){
> $scope.modelObjs = MyService.getModelObjs();
> });
>
> The part I can't figure out is how I present the service's API to any
> clients. Since the service will be using the $http service and will thus be
> asynchronous, I can't immediately return the model objects so the code
> above would work. I suspect I have to in turn use another promise, but I'm
> at a loss. Does this make sense? Can anyone provide any advice?
>
> --
> You received this message because you are subscribed to the Google Groups
> "AngularJS" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> To post to this group, send email to [email protected].
> Visit this group at http://groups.google.com/group/angular.
> For more options, visit https://groups.google.com/d/optout.
>
--
You received this message because you are subscribed to the Google Groups
"AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.