1

I'm looking to have a bit of a cleaner controller to not muddy it up with promise api stuff.

Here's an example of what I'm talking about:

Some Service

...
.service('SomeService', function SomeService($http) {
  this.getAllItems = function() {
    return $http.get('api/items')
      .success(function(data) {
        return data;
      });

Controller

...
SomeService.getAllItems().then(function(response) {
  $scope.items = response.data;
});
...

I'm trying to avoid the extra function call on the promise and assign items directly like so:

$scope.items = SomeService.getAllItems();

Is this possible? I've tried calling the then within the service, and it still ends up returning a promise object once it's resolved in the controller, but I'm probably doing something wrong. Thanks!

4
  • That would make the call non-async - what's wrong with using .then()? Commented Apr 15, 2014 at 15:56
  • Nothing is "wrong" with it, just feels ... dirty, I don't know. Commented Apr 15, 2014 at 15:57
  • I'm assuming by this comment, the .then() callback delegates once the response is received, otherwise it'd block? Commented Apr 15, 2014 at 15:58
  • If you are using ngRoute you can use the resolve property of the route. Commented Apr 15, 2014 at 16:13

1 Answer 1

1

You can use the $resource class to do it. This is from the documentation

It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view. Having an empty object results in no rendering, once the data arrives from the server then the object is populated with the data and the view automatically re-renders itself showing the new data. This means that in most cases one never has to write a callback function for the action methods.

Sign up to request clarification or add additional context in comments.

1 Comment

Hrm, this might be exactly what I'm looking for!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.