如何将消息从一个模块发送到另一个模块?

How to send message from one module to another?

angular是否有任何模块间通信的集成解决方案? 如何将数据从一个模块发送到另一个模块?也许有一些事件循环?

我会有一个通用模块,您的两个通信模块将依赖该模块。 公共模块将通过公开 service that can raise and broadcast events to listening modules. See $emit, $on, and $broadcast

来提供中介模式的实现

我个人喜欢利用 "hidden" 事件,这样事件的广播和处理就封装在服务内部了。您可以阅读有关此技术的更多信息 here

示例服务实现:

angular.module('app.core').factory('NotifyService', function($rootScope) {
    return {
        onSomethingChanged: function(scope, callback) {
            var handler = $rootScope.$on('event:NotifyService.SomethingChanged', callback);
            scope.$on('$destroy', handler);               
        },
        raiseSomethingChanged: function() {
            $rootScope.$emit('event:NotifyService.SomethingChanged');
        }
    };
});

确保你的模块依赖于app.core

angular.module('module1', ['app.core']);
angular.module('module2', ['app.core']);

服务使用示例:

angular.module('module1').controller('SomeController', function($scope, NotifyService) {
    NotifyService.onSomethingChanged($scope, function somethingChanged() {
        // Do something when something changed..
    });
});

angular.module('module2').controller('SomeOtherController', function($scope, NotifyService) {

    function DoSomething() {
        // Let the service know that something has changed, 
        // so that any listeners can respond to this change.
        NotifyService.raiseSomethingChanged();
    };
});

为了在 "call function" 而不是 "send event" 方法中实现双向通信,这可以使用服务来实现。诀窍是避免两个模块相互要求 - 这是不允许的。

相反,有效的配置如下所示:

  • 模块 B 需要模块 A
  • 这允许模块 A 中的服务自然地(angular 明智地)注入模块 B 中的函数。这是简单的部分。
  • 模块 A 中的函数无法注入模块 B 中的服务,但是...
  • 可以在模块 A 中定义存根服务(因此同一模块中的函数可以访问)和 "decorate" 在模块 B 中定义这些(实际上是实现这些)

与基于事件的通信不同,这是一种非对称通信模式,它允许接口(模块 A 中定义的服务)和实现(模块 B 中相同服务的装饰版本)之间的解耦。

模块 A 可以这样实现:

// The module itself
angular.module("ModuleA", [])

// A stub service (optional: define "un-decorated" implementation)
.service("someService", function(){
    return {};
})

// Any controller or other function invoking the service
.controller(someController, ["someService", function(someService){
    someService.usefulFunction();
}])

模块 B 可以这样实现:

// The module itself
angular.module("ModuleB", ["ModuleA"])

// Decorate the service in the other module
.decorator("someService", [function(){
    return {
        usefulFunction: function(){
            // Implement function here
        }
    };
}])

备注:

  • 装饰器函数可以用 $delegate 注入,但这不是必需的,只要模块 B 提供模块 A 中服务的完整替换。
  • 此外,装饰器函数可以从模块 A 或 B 中注入任何服务(不仅仅是提供者!),因此对于实际的服务实现没有特别的限制,它基本上可以依赖 AngularJS环境。