각도 1.08을 사용하고 있으므로 responseInterceptors
을 사용해야합니다.Angular에서 인터셉터를 사용하여 오류를 처리하는 일반적인 방법
먼저 코드를 입력하십시오.
통역 :
app.factory('errorInterceptor', ['$q', 'NotificationService', function ($q, NotificationService) {
return function (promise) {
return promise.then(function (response) {
// do something on success
return response;
}, function (response) {
// do something on error
alert('whoops.. error');
NotificationService.setError("Error occured!");
return $q.reject(response);
});
}
}]);
app.config(function ($httpProvider) {
$httpProvider.responseInterceptors.push('errorInterceptor');
});
NotificationService :
app.service("NotificationService", function() {
var error = '';
this.setError = function (value) {
error = value;
}
this.getError = function() {
return error;
}
this.hasError = function() {
return error.length > 0;
}
});
지침 오류 상자 :
app.directive("errorBox", function (NotificationService) {
return {
restrict: 'E',
replace: true,
template: '<div data-ng-show="hasError">{{ errorMessage }}</div>',
link: function (scope) {
scope.$watch(NotificationService.getError, function (newVal, oldVal) {
if (newVal != oldVal) {
scope.errorMessage = newVal;
scope.hasError = NotificationService.hasError();
}
});
}
}
});
문제 : 나는 여러 장소에서 <error-box>
를 사용하는 경우, 모든 상자가 표시됩니다 오류 메시지 이것은 내 의도가 아닙니다. 예외가 발생하는 오류 상자 만 표시하고 싶습니다.
예를 들어, 나는 트랜잭션 목록을 보여주는 지시문을 가지고 있습니다. 트랜잭션을 가져 오는 데 실패 할 때 해당 부분에 선언 된 오류 상자를 표시하려고합니다. 고객을 편집 할 수있는 지침이 있습니다. 이 지정 문에는 error-box 태그도 들어 있습니다.
고객 저장에 실패하면 두 오류 상자가 모두 표시되지만 고객의 오류 상자 만 표시되기를 원합니다.
누군가가 이것을 구현할 생각이 있습니까?
광범위한 답변 주셔서 감사합니다. 이것은 나에게 확실히 생각할 것을 제공합니다. – Martijn