Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communication between angular 2 and pure 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);

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.

like image 273
Vikhyath Maiya Avatar asked Oct 21 '25 11:10

Vikhyath Maiya


1 Answers

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.

like image 164
Estus Flask Avatar answered Oct 23 '25 06:10

Estus Flask



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!