[英]How to listen to $rootscope.$broadcast with $scope
我的$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);
};
....
....
范围已加载。 为什么对广播没有反应?
您尚未显示的代码中可能还存在其他错误,但是侦听事件的代码不正确。 它应该是:
$scope.$on('server_error', function(event, error) {
console.log('handling server_error', error);
});
这是一个显示它有效的工具 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.