如何处理AngularJS中的$ resource服务错误

val*_*lov 96 angularjs angular-resource

我正在向我的API发出请求,我正在使用AngularJS $资源模块.它与$ http不同,所以我不知道如何处理我的错误.

我的服务:

var appServices = angular.module('app.services', ['ngResource']);
appServices.factory('Category', ['$resource',
    function($resource){
        return $resource('/apicategoryerr/?format=:format', {}, {
            query: {
                method: 'GET', 
                params: { format: 'json'}, 
                isArray: true,

            }
        });
    }]);
Run Code Online (Sandbox Code Playgroud)

我的控制器:

...
Category.query(function(data) {
                console.log(data);
            });
...
Run Code Online (Sandbox Code Playgroud)

我想要这样的东西或..如果我的API无效,我不知道如何处理错误..

Category.query().success(function() {
                console.log('success');
            }).error(function() {
                console.log('error');
            });
Run Code Online (Sandbox Code Playgroud)

mar*_*eig 178

您可以将错误处理程序作为第二个参数传递给query.

Category.query(function(data) {}, function() {});
Run Code Online (Sandbox Code Playgroud)

编辑:

为了使事情更清楚,一些例子:

var Resource = $resource('/restapi/resource');

Resource.query(function(data) {
    // success handler
}, function(error) {
    // error handler
});

Resource.query({
    'query': 'thequery'
},function(data) {
    // success handler
}, function(error) {
    // error handler
});

Resource.query().$promise.then(function(data) {
    // success handler
}, function(error) {
    // error handler
});

Resource.query({
    'query': 'thequery'
}).$promise.then(function(data) {
    // success handler
}, function(error) {
    // error handler
});
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法定义所有使用此资源共同的默认错误处理程序(例如"资源未经服务器授权"? (4认同)
  • 在文档中,它看起来更像是第三个参数是错误回调."Resource.action([parameters],[success],[error])"http://docs.angularjs.org/api/ngResource.$resource (2认同)
  • @NicolasJanel您可以定义一个处理它的函数,然后执行```Resource.query().$ promise.then(function(data){},errorFunction)```.您仍然必须在每个使用查询的地方都包含它,但至少每次都不会重新定义它. (2认同)
  • @Kaspar实例方法的返回值,例如`myResource.$ save`和`myResource.$ delete`就是承诺.所以你可以做`myResource.$ save().then(...)`. (2认同)

Nic*_*nel 68

您可以在资源的创建步骤中通过interceptor在方法的描述中添加一个对象来定义错误处理程序,该对象具有responseError链接到您的错误函数的属性.

function resourceErrorHandler(response) { ... }

$resource('/path/:param/', {} , 
{
        'get':    {method:'GET', 
                   interceptor : {responseError : resourceErrorHandler}},
        'save':   {method:'POST'},
        'query':  {method:'GET', isArray:true, 
                   interceptor : {responseError : resourceErrorHandler}},
        'remove': {method:'DELETE'},
        'delete': {method:'DELETE'}
};
Run Code Online (Sandbox Code Playgroud)

where resourceErrorHandler是在get或query方法上调用每个错误的函数.对于提出的问题,get方法是唯一需要的.当然,您可以将其应用于任何操作.

response$ resource存在另一个拦截器以捕获正常响应.

 {'get': {method:'GET', interceptor : {response : resourceResponseHandler}},
Run Code Online (Sandbox Code Playgroud)

拦截器是$http模块的一部分,您可以在他们的文档中进一步阅读它们.