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
461 views
in Technique[技术] by (71.8m points)

How to handle $resource service errors in AngularJS

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');
            });
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

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

...