$resource callback (error and success)

As of a PR on angulars resource and angular 1.2, angular will be switching to a simpler way of performing success / error checking. Instead of attaching callbacks or a $then method, both the Resource.get(..) and instance.get() will support the $promise method, which naturally returns a promise for both.

As of angular 1.2 the $promise feature will go live: $promise changes

Change your “get” request to be something along these lines (original example is on angularjs.org front page):

factory('Project', function($resource) {
  var Project = $resource('https://api.mongolab.com/api/1/databases' +
      '/youraccount/collections/projects/:id',
      { apiKey: 'yourAPIKey' }, {
        update: { method: 'PUT' }
      }
  );

  Project.prototype.update = function(cb) {
    return Project.update({id: this._id.$oid})
      .$promise.then(
        //success
        function( value ){/*Do something with value*/},
        //error
        function( error ){/*Do something with error*/}
      )
  };

  Project.prototype.destroy = function(cb) {
    return Project.remove({id: this._id.$oid})
      .$promise.then(
        //success
        function( value ){/*Do something with value*/},
        //error
        function( error ){/*Do something with error*/}
      )
  };

  return Project;
});

Somewhere else in the a controller you may instantiate a resource “Project” instance where you can use the same interface for successes and errors:

var myProject = new Project();

myProject.$get({id: 123}).
   .$promise.then(
      //success
      function( value ){/*Do something with value*/},
      //error
      function( error ){/*Do something with error*/}
   )

Leave a Comment