简体   繁体   English

如何在 Angular 中使用全局“窗口”?

[英]How do I use global 'window' in Angular?

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我想使用 "window["initMapCallback"] 来调用和监听另一个文件中的 "initMapCallback",但我在调试 window 中遇到错误,它说

Question - How do I correctly use this as "window["initMapCallback"] = function()" is not being triggered.问题- 我如何正确使用它,因为没有触发“window[”initMapCallback“] = function()”。

Uncaught (in promise) TypeError: window.initMapCallback is not a function at initMap ((index):35:32)未捕获(承诺)类型错误:window.initMapCallback 不是 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.如果我从调用中删除“()”,没有错误,但我仍然无法调用或输入 function。

What happens is that the external JS is ready before your Angular app and given component and the function is not yet set.发生的情况是外部 JS 在您的 Angular 应用程序和给定组件之前准备就绪,并且 function 尚未设置。 It's also very wrong.也是大错特错。 Why not try to load the map js inside the Angular and trigger the callback there?为什么不尝试在 Angular 中加载 map js 并在那里触发回调?

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:然后当你需要 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.另一个 Angular 文件的收听方式主要是订阅和服务,你不应该为此使用 window object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM