额外的层可以更好地处理ajax调用

Additional layer to handle ajax calls better

本文关键字:处理 ajax 调用 更好      更新时间:2023-09-26

我的系统工作方式如下;

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
        });
    }

这种方法检查成功与错误的承诺。现在我需要找到一种新的方法来处理我对未接受错误的调用,或者如果错误发生在前端,它不应该到达rest服务。

$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');