$resource 回调(错​​误和成功) [英] $resource callback (error and success)

查看:21
本文介绍了$resource 回调(错​​误和成功)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 AngularJS 1.1.3 来使用带有承诺的新 $resource...

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

我如何从中获得回调?我尝试了与 $http 相同的方法:

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...

我也试过了:

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

即使返回的是 404 ...

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

有什么想法吗?

谢谢

推荐答案

As of a 关于 angulars 的 PR资源 和 angular 1.2,angular 将切换到更简单的方式来执行成功/错误检查.Resource.get(..) 和 instance.get() 都将支持 $promise 方法,而不是附加回调或 $then 方法,这自然会为两者返回一个承诺.

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.

从 angular 1.2 开始,$promise 功能将上线:$promise 更改

将您的获取"请求更改为类似以下内容(原始示例在 angularjs.org 首页上):

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

这篇关于$resource 回调(错​​误和成功)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆