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

2024-02-20

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


我将有一个您的两个通信模块所依赖的通用模块。 公共模块将通过公开一个中介者模式来提供中介者模式的实现。service https://docs.angularjs.org/guide/services可以向监听模块引发和广播事件。看$emit https://docs.angularjs.org/api/ng/type/%24rootScope.Scope#%24emit, $on https://docs.angularjs.org/api/ng/type/%24rootScope.Scope#%24on, and $广播 https://docs.angularjs.org/api/ng/type/%24rootScope.Scope#%24broadcast

我个人喜欢利用“隐藏”事件,以便将事件广播和处理封装在服务内部。您可以阅读有关此技术的更多信息here http://www.codelord.net/2015/05/04/angularjs-notifying-about-changes-from-services-to-controllers/.

服务实施示例:

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();
    };
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何从一个模块向另一个模块发送消息? 的相关文章

随机推荐