Check for Angular Resource Response

I have a service that returns a promise. I would like to check if the return value is empty. How can i achieve this. I think I need to somehow extract the return value from the promise object.

Here is my resource:

app.factory('Auth', ['$resource',
  function($resource) {
    return $resource('/user/identify', {}, {
      identify: {
        url: '/user/identify'
      },
    });
  }
]);

Then in the service:

Auth.identify(function(data) {

  // This always passes since data contains promise propeties
  if (!_.isEmpty(data)) {

  }
});

The console data log gives:

Resource
  $promise: Object
  $resolved: true
  __proto__: Resource

I can check the expected properties when the object is not empty, but would like to use a more general method.

+4
source share
2 answers

To expand the return value, you can directly access the promise:

Auth.identify()
    .$promise
    .then(function(data) {
      if (!_.isEmpty(data)) {
        // ...
      }
    });
0
source

. "" , Resource, Resource, :

$resource('/api/...').get({...}).then(function(response) {
  if (response.data) {
    // the response has a data field!
  }
}

// note: this is using query(), which expects an array
$resource('/api/...').query({...}).then(function(response) {
  if (response.length > 0) {
    // the response data is embedded in the response array
  }
});
0

All Articles