Communication between angular 2 and pure javascript

大城市里の小女人 提交于 2019-12-10 11:44:05

问题


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);

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.


回答1:


The basic communication can be performed via callbacks.

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
    }
  }
}

And/or

window.angularToVanillaCallback = data => {
  // communicate with other vanilla JS code
}

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.

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.



来源:https://stackoverflow.com/questions/47672774/communication-between-angular-2-and-pure-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!