3

What's the best way to handle promises in Angular.js with a resource that expects a query string / parameters passed to it? I've seen the job of $q handled in the factory, controller and router but I'm not sure how to handle it in any case when there's parameters involved.
So if this is the factory :

angular.module(Animals, ['$resource', '$route', '$location', function($resource, $route, $location) {
  return $resource('http://thezoo.com/animals', { query: {method: 'GET', isArray: true}});
}]);

and this is the controller:

Animals.query({size="med",gender='f'});

then how should this best be handled using promises? The call to the external resource can take quite long.

2 Answers 2

3

Really late to the party, but I found this page from Google. If you want to use a resource, but maybe you want to get data from your query method before you continue (maybe you're writing this in a resolve or something), you can do this.

var deferred = $q.defer();
Resource.query({params}, function (response) {
  someData = response;
  deferred.resolve(someData);
});
return deferred.promise;
Sign up to request clarification or add additional context in comments.

4 Comments

There's no need to wrap a $resource in another promise. As of Angular 1.1/1.2, the $promise property of the resource object is fully then-able (and resolve-able), and contains references back to the $resource object itself.
@XMLilley If you were going to use a resource to get a particular object in your resolve, would you just return something like Resource.get($route.current.params.id)?
exactly so. I have an app right now with a Service that does the same thing, including grabbing a value off of $routeParams.
if you are using $resource, you do not need to use $q as promise is already baked in.
1

It's not exactly clear what you're trying to accomplish.

$resource methods will not return promises. They will return empty arrays or objects that are be populated when data is returned by the server.

If you want a method that returns a promise, you can write one that uses $http directly.

Comments

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.