如何处理AngularJS $资源服务错误 [英] How to handle $resource service errors in AngularJS

查看:101
本文介绍了如何处理AngularJS $资源服务错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我提出请求,我​​的API和我使用AngularJS $资源模块。这是从$ HTTP不同,所以我不知道如何处理我的错误。

我的服务:

  VAR appServices = angular.module('app.services',['ngResource']);
appServices.factory('分类',['$资源',
    功能($资源){
        返回$资源('/ apicategoryerr /格式=:格式',{},{
            查询:{
                方法:GET,
                PARAMS:{格式:JSON},
                IsArray的:真实,            }
        });
    }]);

我的控制器:

  ...
Category.query(功能(数据){
                的console.log(数据);
            });
...

我想是这样的..或者我不知道一个方法来处理错误,如果我的API不工作。

  Category.query()。成功(函数(){
                的console.log(成功);
            })错误(函数(){
                的console.log('错误');
            });


解决方案

您可以通过错误处理程序作为第二个参数查询

  Category.query(功能(数据){}功能(){});

编辑:

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

  VAR资源= $资源('/ RESTAPI /资源');Resource.query(功能(数据){
    //成功处理程序
},功能(错误){
    //错误处理程序
});Resource.query({
    '查询':'thequery
},功能(数据){
    //成功处理程序
},功能(错误){
    //错误处理程序
});Resource.query()。$ promise.then(功能(数据){
    //成功处理程序
},功能(错误){
    //错误处理程序
});Resource.query({
    '查询':'thequery
})$。promise.then(功能(数据){
    //成功处理程序
},功能(错误){
    //错误处理程序
});

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

解决方案

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

这篇关于如何处理AngularJS $资源服务错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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