我的$http函数可以返回以下错误:
POST http://foobar.dev/foobar 500 (内部服务器错误) 发布http://foobar.dev/foobar 401 (未经授权)
难道我没有办法抓到所有的状态代码吗?
$http.post('/foobar', form)
.success(function(data, status, headers, config) {
console.info(data);
})
.error(function(data, status, headers, config) {
console.error(data);
if(status === 401) {
$scope.setTemplate('show-login');
}
if(status === 500) {
$scope.setTemplate('server-error');
}
}
); 其中,$scope.setTemplate()是控制器内设置视图的函数。
但是,我必须对每个error()函数这样做,并且有很多类似的函数,它们也没有使它成为干代码:P
我想要的是捕捉错误并根据错误中返回的状态代码执行操作。
FYI:我不使用天使$routeProvider()。
发布于 2015-12-02 13:40:28
您可以使用角度$http拦截器来实现这一点,如@Dalorzo解释的那样:
var myApp = angular.module("myApp", [], ['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push(['$rootScope', '$q', function($rootScope, $q) {
return {
'responseError': function(response) {
var status = response.status;
// Skip for response with code 422 (as asked in the comment)
if (status != 422) {
var routes = {'401': 'show-login', '500': 'server-error'};
$rootScope.$broadcast("ajaxError", {template: routes[status]});
}
return $q.reject(response);
}
};
}]);
});然后在您的控制器中接收它:
$scope.$on("ajaxError", function(e, data) {
$scope.setTemplate(data.template);
});现在,您不必将每个error函数都放入其中。
发布于 2015-12-02 13:29:21
不如这样吧:
var routes = {'401':'show-login', '500': 'server-error'};
$scope.setTemplate(routes[status]);其中,routes是一个包含错误代码和所需路由的字典。
发布于 2015-12-02 13:39:41
这正是$http拦截器的用途。请参阅此处的拦截器部分:$http
基本上,您可以为所有$http请求创建通用功能,在其中您可以处理不同的状态。例如:
// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2){
return {
response: function(response){
// do something for particular error codes
if(response.status === 500){
// do what you want here
}
return response;
}
};
});
// add the interceptor to the stack
$httpProvider.interceptors.push('myHttpInterceptor');https://stackoverflow.com/questions/34043892
复制相似问题