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);
});