angular 2和纯javascript之间的通信 [英] Communication between angular 2 and pure javascript
问题描述
我正在构建一个有角度的应用程序,并且处于必须与外部javascript通信的情况下.
I am building an angular application and i am in a situation where i have to communicate with an external javascript.
场景 在应用初始化期间,我使用
Scenario During app initialization, i inject two iframes into index.html using
document.body.appendChild(iframe);
我的脚本在index.html中运行,并且具有多种功能,其中之一是getData();当应用程序初始化时,我必须从有角度的应用程序组件中向该函数发送数据.怎么办呢?我知道如何从javascript到angular进行通信,但反之则不行.请帮我.我被感动了.
I have script running in index.html and has a multiple functions among which one is getData(); I have to send data to this function from the angular app component when the app initialises. How to go about this ? I know how to communicate from javascript to angular but not the other way round. Please help me. I am struck.
推荐答案
基本通信可以通过回调执行.
The basic communication can be performed via callbacks.
可以通过Angular或非Angular应用程序定义回调.取决于沟通的方向.
A callback can be defined either by Angular or non-Angular application. depending on the direction of communication.
@Injectable()
class GlobalService {
constructor() {
window.vanillaToAngularCallback = data => {
// communicate with other Angular providers
}
}
}
和/或
window.angularToVanillaCallback = data => {
// communicate with other vanilla JS code
}
其中angularToVanillaCallback
应该在Angular内部调用,而vanillaToAngularCallback
应该在Angular外部调用.第一次回调调用的时间应正确选择;回调函数不应由一侧调用,直到它们将由另一侧定义为止.
Where angularToVanillaCallback
is supposed to be called inside Angular, and vanillaToAngularCallback
is called outside Angular. The time of first callback calls should be chosen correctly; callbacks shouldn't be called by one side until they will be defined by another side.
仍然最好将非角度部分保留为Webpack捆绑包.这样可以避免引用window
,并且可以通过回调或RxJS主题将通用类用于与Angular部件进行通信.
It's still preferable to keep non-Angular part as a Webpack bundle. This way the reference to window
can be avoided, and common classes can be used for communication with Angular part, either via callbacks or RxJS subjects.
这篇关于angular 2和纯javascript之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!