-1

I want to use "window["initMapCallback"] to call and listen for "initMapCallback" in another file, but I'm getting an error in the debug window that says

Question - How do I correctly use this as "window["initMapCallback"] = function()" is not being triggered.

Uncaught (in promise) TypeError: window.initMapCallback is not a function at initMap ((index):35:32)

<script>
  function initMap() {
    window["initMapCallback"](); // error here!
  }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=secret-key&libraries=places&callback=initMap" type="text/javascript" async defer></script>

In the component where I want to listen and receive it I have this

ngOnInit() {
  window["initMapCallback"] = function() {
    console.log('listener entered');
  };
}

If I remove the "()" from the call, there is no error but I still don't get the function to be called or entered into.

chuckd
  • 13,460
  • 29
  • 152
  • 331

1 Answers1

1

What happens is that the external JS is ready before your Angular app and given component and the function is not yet set. It's also very wrong. Why not try to load the map js inside the Angular and trigger the callback there?

public loadScript(url: string, callback: () => void): void {
  if (document.querySelector(`script[src="${url}"]`)) {
    callback();
    return;
  }
  const script = document.createElement('script');
  script.onload = callback();
  script.src = url;
  document.body.appendChild(script);
}

And then when you need the map:

this.loadScript(
  "https://maps.googleapis.com/maps/api/js?key=secret-key&libraries=places",
  () => {
    // some callback, usually subscription in a service
  }
);

The way for another Angular file to listen is mostly with subscriptions and services, you should not use the window object for this.

Julian
  • 11
  • 2