Search code examples
javascriptangularjspromiseangular-resource

Resolve Angular resource promise


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.


Solution

  • 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());
      });
    };