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)
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
模块的一部分,您可以在他们的文档中进一步阅读它们.
归档时间: |
|
查看次数: |
83376 次 |
最近记录: |