使用AngularJS发布订阅服务

Publish Subscribe service using AngularJS

本文关键字:服务 布订阅 AngularJS 使用      更新时间:2024-07-05

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

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,我该如何执行?

如果我理解正确,您希望将值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

这是对这个问题的回答:在AngularJS 中显示有关气泡图D3.js的信息