Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

javascript - $resource callback (error and success)

I′m using AngularJS 1.1.3 to use the new $resource with promises...

How can I get the callback from that? I tried the same way I did with $http :

$resource.get('...').
  success(function(data, status) {
      alert(data);
   }).
   error(function(data, status) {
      alert((status);
   });

But there is no 'success' neither 'error' functions...

I also tried that :

$resource.get({ id: 10 },function (data) {
   console.log('success, got data: ', data);
 }, function (err) {
   alert('request failed');
 });

That always print "success, got data" even if the return is a 404 ...

Any idea?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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*/}
   )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...