我的系统如下所示;
StatisticService
我的服务层中只有http调用,并收集要在控制器中使用的数据。
angular.module('app').factory('StatisticService', ['$http', 'CONFIG', function ($http, CONFIG) {
var urlBase = CONFIG.API_END_POINT + '/statistics';
return {
getReport : function (data) {
return $http.post( CONFIG.API_END_POINT + '/reports/mainReport', data);
}
}
}]);
StatisticController
function init() {
var mediaAccounts = MediaAccountService.findAll(),
searchQueryList = SearchQueryService.getAll(),
tags = TagService.getAllActiveTags(),
dates = $scope.CacheService.getData('dateFormats');
$q.all([mediaAccounts, searchQueryList, tags, dates])
.then(function (result) {
$scope.mediaAccounts.push.apply($scope.mediaAccounts, result[0].data.resultData);
$scope.searchQueryList = result[1].data.resultData;
$scope.tags = result[2].data.resultData;
$scope.dateFilter = result[3];
$scope.dateFilter.selected = $scope.dateFilter[1];
}).then(function () {
$scope.refreshChart();
});
}
对于get方法有一个init函数,并且在我有很多post方法之后用静态数据填充我的控制器;
function getReport(type) {
return StatisticService.getReport({
statisticType: type,
dateFormat: $scope.dateFilter.selected,
startDate: $scope.date.startDate.output('time'),
endDate: $scope.date.endDate.output('time'),
tagList: $scope.query.tagList,
searchQueryList: $scope.query.searchQueryList,
userIdList: $scope.query.userIdList
});
}
此方法检查成功和错误承诺。现在我需要找到一种新的方法来处理我对未解决的错误的调用,或者如果前端发生错误,它不应该到达休息服务。
答案 0 :(得分:1)
$Http Interceptors - 出于全局错误处理,身份验证或任何类型的请求或后处理响应的同步或异步预处理的目的,希望能够在请求被移交给请求之前拦截请求。服务器和响应在移交给发起这些请求的应用程序代码之前。拦截器利用promise API来满足同步和异步预处理的需求。
来自Angular docs:
// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
// optional method
'request': function(config) {
// do something on success
return config;
},
// optional method
'requestError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
},
// optional method
'response': function(response) {
// do something on success
return response;
},
// optional method
'responseError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('myHttpInterceptor');