【问题标题】:How to listen to $rootscope.$broadcast with $scope如何使用 $scope 收听 $rootscope.$broadcast
【发布时间】:2016-08-09 02:49:17
【问题描述】:

我的$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);
        };

        ....

        ....

范围已加载。为什么它对广播没有反应?

【问题讨论】:

    标签: angularjs angularjs-rootscope angular-broadcast


    【解决方案1】:

    您未显示的代码中可能存在其他错误,但您的代码监听事件不正确。应该是:

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

    这里是a plunkr showing that it works

    【讨论】:

    • 啊-我怎么会错过那个括号...?!谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-30
    • 2018-03-16
    • 2016-06-09
    相关资源
    最近更新 更多