问题描述
我想创建一个函数来获取位置值使用下面的共享服务将它传递给所有的组件是我的 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.variable任何变量,它的JavaScript这个发行股份价值this.setvalue功能。我不能连得此功能与我的构造函数来工作,它在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
-callback关键字这个
指向自动完成实例。
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);
});
这篇关于打字稿逻辑问题具有角2和谷歌地图API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!