如何处理 AngularJS 中的 $resource 服务错误 [英] How to handle $resource service errors in AngularJS
本文介绍了如何处理 AngularJS 中的 $resource 服务错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在向我的 API 发出请求,并且我正在使用 AngularJS $resource 模块.它与 $http 不同,所以我不知道如何处理我的错误.
我的服务:
var appServices = angular.module('app.services', ['ngResource']);appServices.factory('Category', ['$resource',功能($资源){return $resource('/apicategoryerr/?format=:format', {}, {询问: {方法:'获取',参数:{格式:'json'},isArray: 真,}});}]);
我的控制器:
<预><代码>...类别.查询(功能(数据){控制台日志(数据);});...我想要这样的东西,或者..如果我的 API 不起作用,我不知道如何处理错误..
Category.query().success(function() {console.log('成功');}).错误(函数(){console.log('错误');});
解决方案
您可以将错误处理程序作为第二个参数传递给query
.
Category.query(function(data) {}, function() {});
为了让事情更清楚一些,举几个例子:
var Resource = $resource('/restapi/resource');资源查询(功能(数据){//成功处理}, 函数(错误){//错误处理程序});资源查询({'查询':'查询'},函数(数据){//成功处理}, 函数(错误){//错误处理程序});Resource.query().$promise.then(function(data) {//成功处理}, 函数(错误){//错误处理程序});资源查询({'查询':'查询'}).$promise.then(function(data) {//成功处理}, 函数(错误){//错误处理程序});
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 中的 $resource 服务错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文