AngularJS는 모든 $http JSON 응답을 가로채다
Angular를 사용하여 만든 응용 프로그램이 있습니다.JS 및 모든 요청을 JSON 형식으로 전달하는 서버 측 백엔드.각 요청은 해당 요청에 고유한 데이터를 포함하는 데이터 변수를 포함하는 JSON 컨테이너로 래핑됩니다.다른 데이터는 응용 프로그램 내에서 상태 및 제어를 유지하기 위해 사용되며 오류 및 성공 메시지를 확인하고 세션플래그를 확인합니다.이러한 다른 모든 변수는 모든 요청과 함께 처리되며 데이터 변수가 처리되기 전에 먼저 검사됩니다.
현재 JSON 응답의 내용을 먼저 검토하고 데이터 자체를 검토하는 방법이 있습니다.
$http.get('something.json').success(function(response) {
var data = examineJSONResponse(response);
//do the data stuff
});
이것은 유효하고, 시험 J.SONResponse는 코드를 확인하고 문제가 있을 경우 예외를 발생시키고 window.location.href를 사용하여 페이지를 새로고침합니다.
Angular 내에서 이를 자동화할 수 있는 방법이 있습니까?JS는 $http 호출이 이루어질 때마다 이를 확인하고 데이터 변수 내용만 JSON 응답으로 반환하도록 합니다.
인터셉터를 추가하여 응답을 인터셉트할 수 있습니다.$httpProvider.interceptorsAngular 1.1.4+를 사용합니다(요격기 검색은 여기를 참조하십시오).
json과 같은 특정 콘텐츠유형의 경우 콜이 성공하더라도 변경을 거부하거나 예외를 발생시킬 수 있습니다.수정이 가능합니다.response.data컨트롤러 코드에도 전달됩니다.
myModule.factory('myHttpInterceptor', function ($q) {
return {
response: function (response) {
// do something on success
if(response.headers()['content-type'] === "application/json; charset=utf-8"){
// Validate response, if not ok reject
var data = examineJSONResponse(response); // assumes this function is available
if(!data)
return $q.reject(response);
}
return response;
},
responseError: function (response) {
// do something on error
return $q.reject(response);
}
};
});
myModule.config(function ($httpProvider) {
$httpProvider.interceptors.push('myHttpInterceptor');
});
메모: 1.1.4 이전 버전에 대한 답변은 다음과 같습니다.responseInterceptorsAngular 1.1.4)에서는 폐지되었습니다.
더 나은 방법이 있을 수 있지만, 이 게시물과 유사한 작업을 http response interceptor(여기서 설명됨) (json과 같은 특정 콘텐츠 유형)에서 수행할 수 있습니다. 이 경우 콜이 성공하더라도 변경을 거부하거나 예외를 발생시킬 수 있습니다.수정이 가능합니다.response.data여기서도 컨트롤러 코드로 전달됩니다.
myModule.factory('myHttpInterceptor', function ($q) {
return function (promise) {
return promise.then(function (response) {
// do something on success
if(response.headers()['content-type'] === "application/json; charset=utf-8"){
// Validate response if not ok reject
var data = examineJSONResponse(response); // assumes this function is available
if(!data)
return $q.reject(response);
}
return response;
}, function (response) {
// do something on error
return $q.reject(response);
});
};
});
myModule.config(function ($httpProvider) {
$httpProvider.responseInterceptors.push('myHttpInterceptor');
});
또 다른 해결책은 서비스를 생성하여 $http 변수 주변에서 사용하는 것입니다.
angular.module('App', [])
.factory('myHttp',['$http',function($http) {
return function(url, success, failure) {
$http.get(url).success(function(json) {
var data = examineJSONResponse(json);
data && data.success ? success() : failure();
}).error(failure);
);
}
}]);
이것은, 다음과 같이 불릴 수 있습니다.
myHttp(url, onSuccess, onFailure);
언급URL : https://stackoverflow.com/questions/11956827/angularjs-intercept-all-http-json-responses
'source' 카테고리의 다른 글
| Http 헤더에서의 Json 문자열 사용 (0) | 2023.02.26 |
|---|---|
| springboot 2.3.0(h2 데이터베이스에 연결 중) (0) | 2023.02.26 |
| 반응 MUI로 TextField 구성 요소의 너비를 재정의하려면 어떻게 해야 합니까? (0) | 2023.02.26 |
| AJAX 요청의 상대 URL (0) | 2023.02.26 |
| 「」의 삭제"「」의 삭제"「」의 삭제" ★★★★★★★★★★★★★★★★★」 ★★★★★★★★★★★★★★★★★」 ★★★★★★★★★★★★★★★★★」WordPress 시 word word word wordWord.. (0) | 2023.02.18 |