2013-10-18 3 views
2

각도 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 태그도 들어 있습니다.

고객 저장에 실패하면 두 오류 상자가 모두 표시되지만 고객의 오류 상자 만 표시되기를 원합니다.

누군가가 이것을 구현할 생각이 있습니까?

답변

3

각도 서비스는 각도 문서 here에 설명 된 것처럼 단일 개체입니다. 즉, Angular는 서비스의 하나의 "전역"인스턴스 만 만들고 해당 서비스가 요청 될 때마다 동일한 인스턴스를 사용합니다. 즉, Angular는 NotificationService 서비스의 인스턴스 하나만 생성 한 다음 해당 인스턴스를 errorBox 지시어의 모든 인스턴스에 제공합니다. 따라서 하나의 지시문이 NotificationService의 오류 값을 업데이트하면 모든 <error-box 지시문에 해당 값이 적용됩니다. 그래서

, 당신은 각 오류 유형에 대해 여러 알림 서비스를 생성하거나 할 겁니다 (즉, 등 TransactionNotificationCustomerNotification) 또는에 당신이 특정 경고를 설정할 수있는 것이 주요 NotificationService (예 : 서로 다른 방법을 추가 NotificationService.setCustomerError() 또는 NotificationService.setTransactionError()).

이러한 옵션 중 특히 사용자 친화적이거나 깨끗하지는 않지만 나는 (서비스 설정 방식에 따라) 그렇게 할 수있는 유일한 방법이라고 생각합니다.

업데이트 : 그것에 대해 생각 후, 난 그냥 전체 NotificationService 클래스를 삭제하고 그냥 오류가 발생할 때 <error-box> 요소를 통지 $scope 이벤트를 사용하는 것이 좋습니다 수 있습니다

을에 'errorInterceptor' :

app.factory('errorInterceptor', ['$q', '$rootScope', function ($q, $rootScope) { 
    return function (promise) { 
     return promise.then(function (response) { 
      // do something on success 
      return response; 
     }, function (response) { 
      // do something on error 
      alert('whoops.. error'); 
      var errorType = ...; // do something to determine the type of error 
      switch(errorType){ 
       case 'TransactionError': 
        $rootScope.$emit('transaction-error', 'An error occurred!'); 
        break; 
       case 'CustomerError': 
        $rootScope.$emit('customer-error', 'An error occurred!'); 
        break; 
       ... 
      } 

      return $q.reject(response); 
     }); 
    } 
}]); 

그런 다음 귀하의 errorBox 지시문에 :

link: function (scope, element, attrs) { 
     var typeOfError = attrs.errorType; 
     scope.$on(typeOfError, function (newVal, oldVal) { 
      if (newVal != oldVal) { 
       scope.errorMessage = newVal; 
      } 
     }); 

    } 

그리고 나서보기 :

<error-box error-type="transaction-error"></error-box> 
<error-box error-type="customer-error"></error-box> 

의미가 있습니까?

+0

광범위한 답변 주셔서 감사합니다. 이것은 나에게 확실히 생각할 것을 제공합니다. – Martijn

관련 문제