且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在同一页面上的 Angular 应用程序和非 Angular 应用程序之间进行通信?

更新时间:2023-11-22 17:35:52

当我开始将我正在处理的项目迁移到 Angular 时,我遇到了同样的问题.我必须与我的非角度应用程序就不同类型的事件进行通信,例如点击.如果您想使用已知的设计模式,您可以使用中介者模式".它是一种基于发布/订阅的通信.您可以拥有中介者的单例全局实例,并从 angular 和非 angular 应用程序访问它

I had the same problem when I started to migrate the project I am working on to Angular. I had to communicate on different type of events like clicks with my non angular app. If you would like to use a known design pattern you can go with "Mediator pattern". It is a publish/subscribe based communication. You can have a singleton global instance of the mediator and access it from both angular and your non-angular app

这是该库的链接:http://thejacklawson.com/Mediator.js/

在您的应用(两者)加载之前,您可以执行以下操作:

Before your app (both of them) loads you can do something like this:

window.mediator = new Mediator();

稍后你可以在你的 Angular 应用程序中拥有这样的服务:

Later you can have in your Angular app a service like so:

angular.module()
   .service('mediator', function() {
     var mediator = window.mediator || new Mediator();
     return mediator;
 });

从您的非角度应用程序中,您可以简单地执行以下操作:

And from your non-angular app you can simply do:

mediator.subscribe('something', function(data){ ... });

然后从您的 Angular 控制器或您拥有的任何东西中注入创建的 mediator 服务并像这样使用它:

And from your Angular controller or whatever you have you will inject the mediator service created and use it like so:

mediator.publish('something', { data: 'Some data' });

现在,您的应用之间既有 Angular 通信方式,也有非 Angular 通信方式.

Now you have both an Angular and non-Angular way of communicating between your apps.

这个解决方案给我带来了奇迹.

This solution did wonders for me.