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