如何在同一页面上的Angular应用程序和非Angular应用程序之间通信? [英] How do I communicate between an Angular app and non-angular app on the same page?

查看:79
本文介绍了如何在同一页面上的Angular应用程序和非Angular应用程序之间通信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过用Angular模块将其从Angular版本引导到一个非Angular版本.除了需要与页面的其他部分进行通信之外,它的工作原理非常好.不幸的是,目前我无法将页面的其余部分转换为Angular.

I'm turning a piece of a non-angular web page into an Angular version by angular.bootstrapping it with an Angular module. It works great except for the fact that it needs to communicate with the other parts of the page. Unfortunately I cannot convert the rest of the page to Angular at this time.

到目前为止,我发现最好的方法是在包含我需要传达的信息的自举元素上触发香草JS事件.

The best way I've figured to do this so far is by firing vanilla JS events on the bootstrapped element containing the information I need to communicate.

是否存在确定的模式或更好的方法?

Are there established patterns or better ways of doing this?

推荐答案

当我开始将正在处理的项目迁移到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.

让我知道,干杯!

这篇关于如何在同一页面上的Angular应用程序和非Angular应用程序之间通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆