【问题标题】:Publish Subscribe service using AngularJS使用 AngularJS 发布订阅服务
【发布时间】:2016-04-14 16:28:28
【问题描述】:

我正在使用此代码创建一个工厂,用于在控制器、指令和服务之间发布和订阅消息。

angular.module('app', []);

angular.module('app').controller('TheCtrl', function($scope, NotifyingService) {
    $scope.notifications = 0;

    $scope.notify = function() {
        NotifyingService.publish();
    };

    // ... stuff ...
    NotifyingService.subscribe($scope, function somethingChanged() {
        // Handle notification
        $scope.notifications++;
    });
});

angular.module('app').factory('NotifyingService', function($rootScope) {
    return {
        subscribe: function(scope, callback) {
            var handler = $rootScope.$on('notifying-service-event', callback);
            scope.$on('$destroy', handler);
        },

        publish: function() {
            $rootScope.$emit('notifying-service-event');
        }
    };
});

它工作正常,但我想在发布给订阅它的人时传递数据,我该怎么做。 假设我想发布 4 的值,我该如何执行?

【问题讨论】:

    标签: javascript angularjs publish-subscribe


    【解决方案1】:

    如果我理解正确,您想将值 4 发布到 'notifying-service-event',并且您想在订阅者内部使用该值。

    为了发布一个值,您需要将它传递给您的 emit 函数。

    publish: function(msg) {
                $rootScope.$emit('notifying-service-event', msg);
            }
    

    然后,当你使用这个发布函数时,传递你想要的值。

    node.on("click", click);
    
    function click() {
      NotifyingService.publish(4);
    }
    

    在处理subscribe 事件时:

    NotifyingService.subscribe($scope, function somethingChanged(event,msg) {
            console.log(msg); //4
            scope.number = msg //or whatever you want
            scope.$apply();
        });
    

    您可以在此处找到完整示例:https://plnkr.co/edit/CnoTA0kyW7hWWjI6DspS?p=preview

    这是对问题的回答: Display informations about a bubble chart D3.js in AngularJS

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多