Reputation: 1481
I am using https://github.com/StarterSquad/startersquad.github.com/tree/master/examples/angularjs-requirejs-2 folder structure for app and inside services and I have following code:
define(['./module'], function(services) {
'use strict';
services.factory('user_resources', ['$resource', '$location', function($resource, $location) {
return $resource("", {},
{
'getAll': {method: "GET", url:'JSON/myList.JSON',isArray:true}
});
}]);
});
and in controller I have following code:
define(['./module'], function (controllers) {
'use strict';
controllers.controller('myListCtrl',['Phone','Phone1','loginForm','$scope','$http','user_resources','CreditCard',function(Phone,Phone1,loginForm,$scope,$http,user_resources,CreditCard){
console.log(user_resources.getAll())
}]);
});
which returns [$promise: Object, $resolved: false] how to get data from that?
I have done the same thing which is done in this tutorial, but in my case it returns promises and in tutorial it directly returns data
Upvotes: 0
Views: 2634
Reputation: 1958
Remember to $httpBackend.flush(), the promise will not be resolved until then.
Upvotes: 0
Reputation: 2117
As mentioned, a promise is returned from all the $http services and you need to handle the response instead of the execution.
An example of a similar problem and solution can be seen here: http://angularspot.com/topic/11-post-not-returning-data-to-controller
Upvotes: 0
Reputation: 18193
Note that a $resource
returns you an object immediately, before the data is retrieved from the server. This object has a property called $promise
. When the response is finally received from the server, the $promise
gets resolved and the object will now contain the data.
In your case the console.log()
output prints what it does because you're accessing the object immediately, before the server has had a chance to respond.
You can do several things with the object returned by $resource
:
1) Use it in your views in Angular expressions. When the $promise
gets resolved automatically the view will be updated with no effort on your part. For example:
controller:
$scope.users = user_resources.getAll();
HTML:
<ul>
<li ng-repeat="user in users">{{user.name}}</li>
</ul>
2) Use the then()
function as suggested by @doodeec above, but with the correct syntax:
user_resources.getAll().$promise.then(function(data) {
// do something with data
});
Upvotes: 4