How to handle $resource service errors in AngularJS

♀尐吖头ヾ 提交于 2019-11-26 11:56:29

问题


I am making requests to my API and I am using AngularJS $resource module. It\'s different from $http so I don\'t know how to handle my errors.

My service:

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,

            }
        });
    }]);

My Controller:

...
Category.query(function(data) {
                console.log(data);
            });
...

I want something like this or .. I don\'t know a way to handle errors if my API is not working..

Category.query().success(function() {
                console.log(\'success\');
            }).error(function() {
                console.log(\'error\');
            });

回答1:


you can pass the error handler as a second parameter toquery.

Category.query(function(data) {}, function() {});

EDIT:

to make things a bit clearer, some examples:

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
});



回答2:


You can define a error handler at the creation step of the resource by adding an interceptor object in the description of a method, with a responseError property, linked to your error function.

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'}
};

where resourceErrorHandler is a function called on each error on get or query method. For the problem asked, the get method is the only needed. Of course you can apply that to any action.

An other interceptor response exists for $resource to catch a normal response.

 {'get': {method:'GET', interceptor : {response : resourceResponseHandler}},

Interceptors are part of the $http module, you can further read about them in their docs.




回答3:


Here is a new ES6 example (I use TypeScript) on my ng.resource

resolve: {
    detail: function (myService, $stateParams) {
        return myService.getEventDetail({ id: $stateParams.id }).$promise.then(data => data, error => false );
    }
}

and then in my controller, 'detail' injected into the controller will either resolve to the data (good) or false for error, where I handle the display of 404.



来源:https://stackoverflow.com/questions/20584367/how-to-handle-resource-service-errors-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!