2016-04-17 13 views
0

私の$scope.$on(...は放送を受けていないようです。

私はHTTPレスポンスエラーをキャプチャするためのインターセプタを持っており、メインコントローラが対応できるイベントをブロードキャストしています。

(function() { 
    'use strict'; 

    angular 
     .module('app') 
     .factory('httpErrorInterceptor', httpErrorInterceptor); 

    httpErrorInterceptor.$inject = ['$rootScope', '$q']; 

    function httpErrorInterceptor($rootScope, $q) { 
     return { 
      responseError: function (rejection) { 
       var firstDigit = rejection.status.toString().substr(0, 1); 

       if (firstDigit === "4") { 
        $rootScope.$broadcast('client_error', rejection); 
       } 
       else if (firstDigit === "5") { 
        $rootScope.$broadcast('server_error', rejection); 
       } 

       return $q.reject(rejection); 
      } 
     }; 
    } 
})(); 

私のアプリでは、無効なデータを意図的にAPIに送信し、httpを400に戻しています。

$rootScope.$broadcast('client_error', rejection);がヒットしているChromeデベロッパーツールで確認できます。

問題は、これが打たれていないということです。

(function() { 
    'use strict'; 

    angular 
     .module('app') 
     .controller('main', main); 

    main.$inject = ['$scope', '$window', 'authenticationService', 'shoppingBasketService']; 

    function main($scope, $window, authenticationService, shoppingBasketService) { 
     // Scope functions. 
     $scope.$on('server_error'), function (event, error) { 
      console.log('handling server_error', error); 
     }; 

     $scope.$on('client_error'), function (event, error) { 
      console.log('handling client_error', error); 
     }; 

     .... 

     .... 

範囲がロードされています。なぜそれは放送に反応しないのですか?

答えて

2

表示されていないコードには他のエラーがありますが、イベントをリッスンしているコードが間違っている可能性があります。次のとおりです。

$scope.$on('server_error', function(event, error) { 
    console.log('handling server_error', error); 
}); 

ここはa plunkr showing that it worksです。

+0

ああ - どのように私はそのブラケットを見逃しましたか?ありがとうございました。 – PeteGO

関連する問題