Reputation: 472
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.
Upvotes: 3
Views: 4149
Reputation: 131
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;
Upvotes: 3
Reputation: 1226
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.
Upvotes: 1