Question

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 becomes 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.

Était-ce utile?

La solution

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;
}]);

Autres conseils

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top