所以我有一堆执行$ http请求的控制器
但是在每个$ http请求中我都有.error(function(data...){//always the same})
我如何为$ http建立一个“抽象类”?
这将是一直重复的代码
.error(function(){
$scope.flashes = {
server: {
type: "danger",
message: "There was a server error processing your request. Please try again later."
}
};
})
答案 0 :(得分:1)
几周前我添加了同样的问题,我想出了这个解决方案:
我首先创建了一个拦截每个http请求的自定义服务:
.factory('HttpInterceptor', ['$q', '$rootScope', function($q, $rootScope) {
return {
// On request success
request : function(config) {
// Return the config or wrap it in a promise if blank.
return config || $q.when(config);
},
// On request failure
requestError : function(rejection) {
//console.log(rejection); // Contains the data about the error on the request.
// Return the promise rejection.
return $q.reject(rejection);
},
// On response success
response : function(response) {
//console.log(response); // Contains the data from the response.
// Return the response or promise.
return response || $q.when(response);
},
// On response failure
responseError : function(rejection) {
//console.log(rejection); // Contains the data about the error.
//Check whether the intercept param is set in the config array. If the intercept param is missing or set to true, we display a modal containing the error
if (rejection.config && typeof rejection.config.intercept === 'undefined' || rejection.config.intercept)
{
//emitting an event to draw a modal using angular bootstrap
$rootScope.$emit('errorModal', rejection.data);
}
// Return the promise rejection.
return $q.reject(rejection);
}
};
}]);
我还定义了一个自定义配置属性“拦截”,我可以添加到$ http配置对象。当我不想在特定请求上应用此行为时,它很有用。 例如:
var registerResource = $resource('/registration/candidate/register', {}, {query:
{method:'POST', isArray: false, intercept: false }
});
为了获得灵活的解决方案,不要忘记这样做很重要:
return $q.reject(rejection);
因此,如果您想要将两种方式结合起来(拦截+手动处理),您仍然可以在控制器中对您的承诺使用错误回调
最后,我将此服务添加到我的应用程序中:
app.config(['$httpProvider', function($httpProvider) {
// Add the interceptor to the $httpProvider to intercept http calls
$httpProvider.interceptors.push('HttpInterceptor');
}]);
我简化了服务,但你也可以将它用于很多事情。就个人而言,我也用它来:
确保不会触发重复的http请求(如果用户在提交按钮上单击了很多)。
在http调用开始时绘制警报并在结束时关闭它以通知用户处理正在处理(例如导出数据)。
PS:官方文档提到了interceptor
答案 1 :(得分:0)
你可以这样做:
app.service('myHttp', function($http){
return function($scope, httpParameters){
var httpPromise = $http(httpParameters);
httpPromise.error(function(){
$scope.flashes = {
server: {
type: "danger",
message: "There was a server error"
}
}
});
};
});
app.controller('MainCtrl', function($scope, myHttp) {
myHttp($scope, {method: 'GET', url: 'www.google.com'});
});