2016-04-17 107 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

相关问题