angular 2 和谷歌地图 api 的打字稿逻辑问题 [英] typescript logic issue with angular 2 and google maps api

查看:50
本文介绍了angular 2 和谷歌地图 api 的打字稿逻辑问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个函数来获取位置值以将其传递给使用共享服务的所有组件,下面是我的 ngOnInit 函数

i am trying to create a function to get the location value to pass it to all the components using shared service below is my ngOnInit function

   this.input = document.getElementById('google_places_ac');
        var autocomplete = new google.maps.places.Autocomplete(this.input, { types: ['(cities)']});
        google.maps.event.addListener(autocomplete, 'place_changed', function () {
            var place=autocomplete.getPlace();
           this.setValue(place.address_components[3].long_name, place.address_components[2].long_name, place.address_components[1].long_name);

         });

问题是它无法识别与我的共享服务共享值的 this.setvalue 函数或与 this.variable 共享值的任何变量,它的 javascriptthis"问题.我什至无法让这个函数与我的构造函数一起工作,它在 getElmentById 处引发错误.

the problem is that it doesn't recognize this.setvalue function which shares value with my shared service or any variable with this.variable , its javascript "this" issue . and i can not even get this function to work with my constructor, it throws error at getElmentById.

有带有箭头函数的解决方案,但我不知道如何在这种情况下使用它,所以请帮助我..

there are solutions with arrow functions and all but i dont know how to use it in this condition so please help me..

推荐答案

place_changed-回调中,关键字 this 指向 Autocomplete-instance.

Inside the place_changed-callback the keyword this points to the Autocomplete-instance.

您需要创建一个闭包:

var instance    = this, 
    autocomplete;
instance.input  = document.getElementById('google_places_ac');
autocomplete    = new google.maps.places.Autocomplete(instance.input, { 
                     types: ['(cities)']});

google.maps.event.addListener(autocomplete, 'place_changed', function () {
   var place=this.getPlace();
   instance.setValue(place.address_components[3].long_name,          
                     place.address_components[2].long_name, 
                     place.address_components[1].long_name);
});

这篇关于angular 2 和谷歌地图 api 的打字稿逻辑问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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