angular 2 和纯 javascript 之间的通信 [英] Communication between angular 2 and pure javascript

查看:17
本文介绍了angular 2 和纯 javascript 之间的通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个 Angular 应用程序,但我必须与外部 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();当应用程序初始化时,我必须从 angular 应用程序组件向此函数发送数据.如何解决这个问题?我知道如何从 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.

最好将非 Angular 部分保留为 Webpack 包.这样就可以避免对 window 的引用,并且可以使用公共类与 Angular 部分进行通信,通过回调或 RxJS 主题.

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屋!

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