반응형
Angular를 사용하는 글로벌 Ajax 오류 처리기JS
웹사이트가 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를 가지는 Web 사이트를 구축하고 있습니다만, 글로벌 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);
그 회답에 주의해 주세요.요격기는 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
반응형
'programing' 카테고리의 다른 글
Wordpress: OR 연산자를 사용하여 tax_query 다중 용어 (0) | 2023.03.23 |
---|---|
json을 C# 어레이로 변환하시겠습니까? (0) | 2023.03.18 |
Perl에서 단순 해시를 json으로 변환하는 방법 (0) | 2023.03.18 |
spring @Valid Validation 기본 오류 메시지를 커스터마이즈하려면 어떻게 해야 하나요? (0) | 2023.03.18 |
ReactJs - "If" 구성 요소 생성 중...좋은 생각? (0) | 2023.03.18 |