如何在Angular2中异步加载谷歌地图API [英] How to load google maps api asynchronously in Angular2

查看:77
本文介绍了如何在Angular2中异步加载谷歌地图API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常在一个普通的javascript网站中,我可以使用以下脚本来引用google maps api,并使用 initMap 设置回调函数函数c $ c>。

Usually in a plain javascript site, I can use the following script to reference google maps api and set the callback function with initMap.

< script async defer src =https://maps.googleapis.com/maps/api/js? callback = initMap>< / script>

我观察到的是 initMap 在普通javascript网站中的功能在窗口范围之下,并且它可以在脚本参数设置中引用 - ?callback = initMap ,但是一旦我在angular2与一个名为 initMap 的组件方法, initMap 将在我的组件范围内。然后,我在索引中设置的异步加载脚本将无法捕捉到我的组件 initMap 方法。

What I observed is the initMap function in the plain javascript site is under the window scope, and it can be referenced in the script parameter settings - ?callback=initMap, but once I write a component in angular2 with a component method called initMap, the initMap will be under the scope of my component. Then the async loading script I set up in the index will not be able to catch my component initMap method.


< PS:我知道 alpha 中有一个 angular2-google-maps 组件可以通过 npm ,但它目前的运行能力有限,所以我想知道如何在不使用其他组件的情况下以更简单的方式加载它,以便我可以使用Google Maps API来实现我的项目。

PS: I know there is an angular2-google-maps component available in alpha via npm, but it currently is shipped with limited capability, so I 'd like to know how to load it in an easier way without using another component so I can just use google maps api to implement my project.


推荐答案

我看到你不想要其他组件,以及谷歌apis。我有使用聚合物YouTube数据API的angular2代码。我有帮助让它安装。这是让我开始的 plunker 。我认为硬件部门正在为该回调进行设置,我相信你可以在没有聚合物的情况下完成。这个例子显示了一个棘手的部分,一个角度服务被用来把所有东西都绑起来。

I see you don't want another component, but polymer has components that work well with google apis. I have angular2 code that uses the polymer youtube data api. I had help getting it setup. Here is the plunker that got me started. I think the hardpart is getting setup for that callback, I'm sure you can do it without polymer. The example shows the tricky part an angular service is used to hook everything up.

    const url = 'https://apis.google.com/js/client.js?onload=__onGoogleLoaded'

    export class GoogleAPI {
      loadAPI: Promise<any>
      constructor(){
        this.loadAPI = new Promise((resolve) => {
          window['__onGoogleLoaded'] = (ev) => {
            console.log('gapi loaded')
            resolve(window.gapi);
          }
          this.loadScript()
        });
        
      }
      
      doSomethingGoogley(){
        return this.loadAPI.then((gapi) => {
          console.log(gapi);
        });
      }
      
      loadScript(){
        console.log('loading..')
        let node = document.createElement('script');
        node.src = url;
        node.type = 'text/javascript';
        document.getElementsByTagName('head')[0].appendChild(node);
        
      }
    }

这篇关于如何在Angular2中异步加载谷歌地图API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆