我的系统工作原理如下;
统计服务
我的服务层中只有 http 调用并收集数据以在 Controller 中使用。
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);
}
}
}]);
统计 Controller
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 方法之后用静态数据填充我的 Controller ;
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
});
}
此方法检查成功和错误 promise 。现在我需要找到一种新方法来处理针对未异常(exception)错误的调用,或者如果前端发生错误,则它不应到达其余服务。
最佳答案
$Http Interceptors - 出于全局错误处理、身份验证或任何类型的同步或异步请求预处理或响应后处理的目的,希望能够在将请求传递给服务器之前拦截请求,并在将响应传递给服务器之前拦截响应到发起这些请求的应用程序代码。拦截器利用 Promise API 来满足同步和异步预处理的需求。
来自 Angular 文档:
// 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');
关于javascript - 更好地处理 ajax 调用的附加层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36279358/