3

I'm having an issue using Angular's $resource service. Since my API sends back a complete response (headers etc), along with an error field in the data Object, I need to get a specific object from the response. This is fairly simple to do with the $http service but I don't understand where to grab these parameters with the $resource service. Below is the working $http request.

$http({
  method  : 'GET',
  url     : 'http://api.discussorama.com/v1/topics',
  headers : {'X-Api-Secret': 'xxx', 'Authorization': 'xxx', 'Content-Type': 'application/x-www-form-urlencoded'}  
})
.then(function(response) {
  console.log(response);
  $scope.topics = response.data.topics;
});

And this is my unsuccessful attemt at the same request with $resource:

var Topic = $resource('http://api.discussorama.com/v1/topics/:id', {id: '@id'}, {
  query: {
    isArray: false,
    method: 'GET',
    headers: {'X-Api-Secret': 'xxx', 'Authorization': 'xxx', 'Content-Type': 'application/x-www-form-urlencoded'}
  }
 });

var response = Topic.query();
$scope.topics = response.topics;
console.log(response);

EDIT: After updating the above code this is what I get in the console.

f {$promise: Object, $resolved: false, $get: function, $save: function, $query:    function…}
  $promise: Object
  $resolved: true
  error: false
  topics: Array[10]
  __proto__: f

However if I change the console log to:

console.log(response.topics);

The console simply returns:

undefined

Where am I going wrong with this? If it helps the link to the page in question is http://hwaelapps.com/discuss/web

Pavel Rogala
  • 163
  • 3
  • 12

1 Answers1

5

You are not handling the promise that $resource hands back. It needs to be handled like your $http call above.

var Topic = $resource('http://api.discussorama.com/v1/topics/id', { id: '@id'}, {
  query: {
    isArray: false,
    method: 'GET',
    headers: {'X-Api-Secret': 'xxx', 'Authorization': 'xxx', 'Content-Type': 'application/x-www-form-urlencoded'}
  }
});

var response = Topic.query();
response.$promise.then(function(data){
    $scope.topics = data.topics; //Changed data.data.topics to data.topics
});
Pavel Rogala
  • 163
  • 3
  • 12
MBielski
  • 6,628
  • 3
  • 32
  • 43
  • Oddly with the above code I get: TypeError: Cannot read property 'then' of undefined. I also updated the question with some more data from the console. Maybe there's something more to explain my situation. – Pavel Rogala Apr 25 '14 at 21:32
  • It seems that the topics data is returned outside of the promise, if that's a possibility. – Pavel Rogala Apr 25 '14 at 21:38
  • Sorry, forgot the $ in front of the promise. Answer updated. (I have this pattern in daily use, so you'd think I'd remember it.) – MBielski Apr 25 '14 at 21:39
  • Thank you so much. That solved my problem. I adjusted your code a bit above from data.data.topics to data.topics. I probably explained it wrong in my original question. Thanks again. – Pavel Rogala Apr 25 '14 at 21:43