admin管理员组

文章数量:1429735

So with a factory I'm making a RESTful GET request using $resource, and I'm not getting the data back.

Initially, I get returned $promise and $resolved: false. $resolved eventually bees true.

I know the url, and headers work because I tested them in the advanced client chrome extension and it works fine. Data is show and everything.

Here is my factory set up, and below that is what I'm referencing in my controller to store it inside a scope variable.

So with a factory I'm making a RESTful GET request using $resource, and I'm not getting the data back.

Initially, I get returned $promise and $resolved: false. $resolved eventually bees true.

I know the url, and headers work because I tested them in the advanced client chrome extension and it works fine. Data is show and everything.

Here is my factory set up, and below that is what I'm referencing in my controller to store it inside a scope variable.

Share Improve this question edited Apr 11, 2014 at 2:07 user_909 asked Apr 1, 2014 at 20:49 user_909user_909 572 silver badges8 bronze badges 1
  • I am facing the same issue and none of the suggested answers work for me. Here is what I get : Object { $promise: Object, $resolved: true, 1421589555: true } where the real data is the last entry. – harry Commented Jan 22, 2015 at 13:39
Add a ment  | 

3 Answers 3

Reset to default 3

The $resource returns a two-level object. In your controller, it needs to be handled like so:

$scope.terms = GetValues.get();
$scope.terms.$promise.then(function(data){
     //This is where things that happen upon success go
}, function(data){
     //This is where things that happen upon error go
});

You could also write your Service to return as follows and eliminate the $promise from your controller:

.factory('GetValues', ['$resource', function($resource){
// search term is :text
return $resource(apiURL,   {}, {
    get:{
      method: 'GET',
      isArray:true,
      headers: {
          'x-auth-token': 'xxxxx',
          'x-auth-user':  'xxxxx'
      }
    }
  }).$promise;
}]);

You need to utilize the callbacks from $resource:

GetValues.get({}, function(data) {
    $scope.terms = data;
})

The $resource constructor returns a promise to actual call. You have to set up the resolve callback for the promise in your controller.

GetValues.get({}, '', function (getResult) {
    // do something with array
    alert(getResult);
}, function (error) {
    console.error('Error getting values', error);
});

The second function is an error callback for the request.

Also, try registering the method with another name, as it isn't very 'nice' to override the native get that expects an object instead of an array:

return $resource(apiURL,{},{ getValues:{
    method: 'GET',... 

And invoke it using

GetValues.getValues().then(... 

PD: there is no need to explicitly return the .$promise

本文标签: javascriptAngularJS resource only won39t return dataStack Overflow