Programing

AngularJS를 사용한 글로벌 Ajax 오류 처리기

crosscheck 2020. 9. 24. 07:29
반응형

AngularJS를 사용한 글로벌 Ajax 오류 처리기


내 웹 사이트가 100 % jQuery 일 때 다음과 같이했습니다.

$.ajaxSetup({
    global: true,
    error: function(xhr, status, err) {
        if (xhr.status == 401) {
           window.location = "./index.html";
        }
    }
});

401 오류에 대한 전역 처리기를 설정합니다. 지금, 나는 함께 AngularJS와를 사용 $resource하고 $http서버 내 (REST) 요청을 할 수 있습니다. angular로 전역 오류 처리기를 유사하게 설정하는 방법이 있습니까?


저는 또한 angular로 웹 사이트를 구축하고 있는데, 글로벌 401 처리에 대해 이와 동일한 장애물을 발견했습니다. 이 블로그 게시물을 보았을 때 http 인터셉터를 사용하게되었습니다. 내가 한 것처럼 도움이 될 것입니다.

"AngularJS (또는 유사) 기반 애플리케이션의 인증." , espeo 소프트웨어

편집 : 최종 솔루션

angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives'], function ($routeProvider, $locationProvider, $httpProvider) {

    var interceptor = ['$rootScope', '$q', function (scope, $q) {

        function success(response) {
            return response;
        }

        function error(response) {
            var status = response.status;

            if (status == 401) {
                window.location = "./index.html";
                return;
            }
            // otherwise
            return $q.reject(response);

        }

        return function (promise) {
            return promise.then(success, error);
        }

    }];
    $httpProvider.responseInterceptors.push(interceptor);

responseInterceptors는 Angular 1.1.4에서 더 이상 사용되지 않습니다. 아래에서 인터셉터를 구현하는 새로운 방법을 보여주는 공식 문서를 기반으로 한 발췌 본을 찾을 수 있습니다 .

$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  return {
    'response': function(response) {
      // do something on success
      return response || $q.when(response);
    },

   'responseError': function(rejection) {
      // do something on error
      if (canRecover(rejection)) {
        return responseOrNewPromise;
      }
      return $q.reject(rejection);
    }
  };
});

$httpProvider.interceptors.push('myHttpInterceptor');

이것은 Coffeescript를 사용하여 내 프로젝트에서 어떻게 보이는지입니다.

angular.module("globalErrors", ['appStateModule']).factory "myHttpInterceptor", ($q, $log, growl) ->
  response: (response) ->
    $log.debug "success with status #{response.status}"
    response || $q.when response

  responseError: (rejection) ->
    $log.debug "error with status #{rejection.status} and data: #{rejection.data['message']}"
    switch rejection.status
      when 403
        growl.addErrorMessage "You don't have the right to do this"
      when 0
        growl.addErrorMessage "No connection, internet is down?"
      else
        growl.addErrorMessage "#{rejection.data['message']}"

    # do something on error
    $q.reject rejection

.config ($provide, $httpProvider) ->
  $httpProvider.interceptors.push('myHttpInterceptor')

다음 <script type="text/javascript" src="../js/config/httpInterceptor.js" ></script>내용으로 파일 만듭니다 .

(function(){
  var httpInterceptor = function ($provide, $httpProvider) {
    $provide.factory('httpInterceptor', function ($q) {
      return {
        response: function (response) {
          return response || $q.when(response);
        },
        responseError: function (rejection) {
          if(rejection.status === 401) {
            // you are not autorized
          }
          return $q.reject(rejection);
        }
      };
    });
    $httpProvider.interceptors.push('httpInterceptor');
  };
  angular.module("myModule").config(httpInterceptor);
}());

참고 URL : https://stackoverflow.com/questions/11971213/global-ajax-error-handler-with-angularjs

반응형