Asynchronous 加载Google Places自动完成异步角度2

Asynchronous 加载Google Places自动完成异步角度2,asynchronous,angular,google-places-api,observable,google-places,Asynchronous,Angular,Google Places Api,Observable,Google Places,我试图在Angular 2组件中实例化一个Google Places自动完成输入。我使用此代码来执行此操作: loadGoogle() { let autocomplete = new google.maps.places.Autocomplete((this.ref.nativeElement), { types: ['geocode'] }); let that = this //add event listener to google autocomplete an

我试图在Angular 2组件中实例化一个Google Places自动完成输入。我使用此代码来执行此操作:

loadGoogle() {
    let autocomplete = new google.maps.places.Autocomplete((this.ref.nativeElement), { types: ['geocode'] });
    let that = this
    //add event listener to google autocomplete and capture address input
    google.maps.event.addListener(autocomplete, 'place_changed', function() {
      let place = autocomplete.getPlace();
      that.place = place;
      that.placesearch = jQuery('#pac-input').val();
    });
    autocomplete.addListener()
  }
通常,我相信,我会使用GoogleAPI提供的回调函数来确保在该函数运行之前加载回调函数,但我无法在组件的范围内访问回调函数。我可以90%的时间加载自动完成输入,但在较慢的连接上,我有时会出错

google is not defined

有没有人在实例化之前知道如何确保在组件中加载GoogleAPI

不确定这是否有帮助,但我只是在index.html中使用了一个简单的脚本标记来加载Google API,我从来没有收到任何错误。我相信你也会这么做。我把我的代码贴在这里,希望对你有所帮助

注意:我使用Webpack加载除GoogleMapAPI之外的其他脚本

<html>
  <head>
    <base href="/">
    <title>Let's Go Holiday</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Google Map -->
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=<your-key>&libraries=places"></script>
  </head>

  <body>
    <my-app>Loading...</my-app>
  </body>
</html>

我使用的方法与上面解释的相同,但根据谷歌页面速度,我得到了这个建议

删除渲染块JavaScript: …es=几何体,位置和区域=IN&语言=en

所以我改变了我的实现

<body>
  <app-root></app-root>
  <script src="http://maps.googleapis.com/maps/api/js?client=xxxxx2&libraries=geometry,places&region=IN&language=en" async></script>
</body>
您还可以做一件事,在收到值(google)后发出事件,并触发您的google任务
在它们里面。

我在应用下面有我的脚本标签,也许这就是问题所在!您好@Andyccs,谢谢您的回答,但我想知道,如果我们使用多个字段输入,会发生什么?它能正常工作吗?你好,C.Kearns,你在angular 2中使用的是哪个api库?google places autocomplete。这个问题一直存在,尚未找到适当的解决办法。
<body>
  <app-root></app-root>
  <script src="http://maps.googleapis.com/maps/api/js?client=xxxxx2&libraries=geometry,places&region=IN&language=en" async></script>
</body>
  triggerGoogleBasedFn(){
    let _this = this;

    let interval = setInterval(() => {
      if(window['google']){
        _this.getPlaces();
        clearInterval(interval);
      }
    },300)
  }