2

I'm running into issues attempting to access the data returned through resource. It appears I am not resolving the promise before accessing the data as my data includes a $promise object and resolved property.

Here is my service:

angular.module('sampleApp')
  .factory('usersService', ['$resource',
    function($resource) {
      var base = '/api/users/:userId/';
      return $resource(base, {}, {
        getLimits: {method: 'GET', url: base + 'limits'},
      });
    }]);

...and the relevant controller code:

var getUserLimits = function() {
  usersService.getLimits({
    userId: userId
  }).$promise.then(function(data) {
    console.log(data);
  });
};

This is what's logged to my console: enter image description here What I'm aiming to get from data is an object containing the deposit, spend, and withdrawal objects.

MattDionis
  • 3,534
  • 10
  • 51
  • 105
  • Why you are not calling object properties directly: `data.deposit`, `data.spend`, `data.widthdrawal`? – Endre Simo Sep 10 '15 at 11:38
  • 1
    @SimoEndre Would cause problems inside a ng-repeat for example, since it would also ouput promise and resolve. – Chrillewoodz Sep 10 '15 at 11:39
  • I could do that, but it makes my code less efficient. Ideally I would like to use `_.each` to iterate through `deposit`, `spend`, and `withdrawal` and perform some data scrubbing. – MattDionis Sep 10 '15 at 11:39
  • 1
    while returning data form server, place those 3 objectcts in on class..so that would be easier to do..`$scope.model = data.myData` then do `$scope.model.deposit` like so..I don;t think so that will cause any issue on the UI;;that will not get printed in `ng-repeat` content,, – Pankaj Parkar Sep 10 '15 at 11:41

1 Answers1

4

on your success callback you can use toJSON() function of $resource response so you will get plain object as you wanted...

var getUserLimits = function() {
  usersService.getLimits({
    userId: userId
  }).$promise.then(function(data) {
    console.log(data.toJSON());
  });
};
MattDionis
  • 3,534
  • 10
  • 51
  • 105
Poyraz Yilmaz
  • 5,847
  • 1
  • 26
  • 28