Pub/Sub 设计模式 angularjs 服务

Pub/Sub design pattern angularjs service

我一直在尝试使用 Mark Rajcok 在此处发布的答案

angular JS - communicate between non-dependend services

我无法理解他的回答。特别是这部分:

angular.forEach(event1ServiceHandlers, function(handler) {
            handler(some_data);
});

event1ServiceHandlers 数组是否填充了在此 forEach 循环中触发的函数(此处称为处理程序)?

我认为通过一个很好的例子可以更容易理解 publish/subscribe 是如何设置的。

我有两个需要通信的服务,但我想避免使用 $rootScope.$broadcast,所以据我所知,pub/sub 服务是最好的方法。我的一个服务需要在我的另一个服务上执行一个功能,但该服务已经将我的第一个服务作为依赖项,因此由于循环依赖性,我不能同时执行相同的两种方式。

我的问题:所以假设你有两个angularjs服务(工厂),如果服务2已经有服务1,服务1如何在服务2上执行一个功能作为依赖。不使用 $broadcast 和 $on

在他的示例中,NotificationService 是任何现有服务都将依赖的新服务。他提供了 Service1 的实现,但 Service2 本质上是相同的......两者都依赖于 NotificationService 并且彼此都不了解。

Service1Service2分别调用NotificationService.onEvent1(event1Happened);订阅事件,调用NotificationService.event1Happened(my_data);.

触发事件

Is the event1ServiceHandlers array populated with functions (here called handler) that is triggered in this forEach loop?

how does service 1 execute a function on service 2 if service 2 already has service 1 as a dependency

像以前一样创建服务 3,NotificationService

.factory('NotificationService', [function() {
    var event1ServiceHandlers = [];
    return {
        // publish
        event1Happened: function(some_data) {
            angular.forEach(event1ServiceHandlers, function(handler) {
                handler(some_data);
            });
        },
        // subscribe
        onEvent1: function(handler) {
            event1ServiceHandlers.push(handler);
        }
    };
}])

让服务 2 向 NotificationService:

注册一个回调函数
.factory('Service2', ['NotificationService',
function(NotificationService) {
    // event1 handler
    var doSomething = function(someData) {
        console.log('S2', someData);
        // do something here
    }
    // subscribe to event1
    NotificationService.onEvent1(doSomething);
    return {
      // define public API for Service2 here
    }
}])

每当服务 1 想要执行服务 2 上的函数 doSomething() 时,它可以发布 event1Happened 事件:

.factory('Service1', ['NotificationService',
function(NotificationService) {
    var someData = ...;
    return {
       // define public API for Service1 here
       callService2Method: function() {
         // publish event
         NotificationService.event1Happened(someData);
       }
    }
}])