2016-04-17 45 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。

我可以在Chrome開發者工具中看到$rootScope.$broadcast('client_error', rejection);正在被擊中。

的問題是,這不是擊中:

(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

相關問題