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

问题描述 投票:3回答:2

棱角分度是否具有用于模块间通信的任何集成解决方案?如何将数据从一个模块发送到另一个模块?也许有一些eventloop?

angularjs messages
2个回答
4
投票

我有一个共同的模块,你的两个通信模块将依赖。公共模块将通过暴露可以向侦听模块提升和广播事件的service来提供Mediator模式的实现。请参阅$emit$on$broadcast

我个人喜欢利用“隐藏”事件,以便将事件广播和处理封装在服务内部。你可以阅读更多关于这种技术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();
    };
});

0
投票

为了在“呼叫功能”而不是“发送事件”方法中实现双向通信,这可以使用服务来实现。诀窍是避免两个模块相互要求 - 这是不允许的。

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

  • 模块B需要模块A.
  • 这允许模块A中的服务自然地(角度方向)可注入模块B中的功能。这是容易的部分。
  • 模块A中的功能不能注入模块B的服务,但......
  • 可以在模块A中定义存根服务(因此可以访问同一模块中的函数)并在模块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环境中的任何内容。
© www.soinside.com 2019 - 2024. All rights reserved.