且构网

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

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

更新时间:2022-05-12 06:15:13

当我开始将正在处理的项目迁移到Angular时,我遇到了同样的问题.我必须与非角度应用程序就不同类型的事件(例如点击)进行交流.如果您想使用已知的设计模式,可以使用Mediator pattern.这是基于publish/subscribe的通信.您可以拥有调解器的单例全局实例,并从有角度的应用程序和非有角度的应用程序中访问它

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, I hope it will help you as well.

让我知道,干杯!