簡體   English   中英

如何使用$ scope收聽$ rootscope。$ broadcast

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM