1
我有一个离子/ angular2应用程序正在运行。有一个谷歌地图加载到视图中。我有一个名为markers
的观察点,它是一个Google地图标记对象的数组。我将它们推到阵列上,让它们出现在地图上。然后我添加事件监听器到所有的标记。点击功能,但是,我失去了访问this.markers
。为什么会发生?也许更好的问题是我如何创建一个可以在整个课程中使用的普通变量?Angular2:失去访问可观察的
这里是我的代码:
export class MapView
{
markers: any;
ngOnInit()
{
//initialization for map and the raw marker array data not shown
this.addListeners()
}
addListeners() //functions properly (this.markers is accessible)
{
console.log(this.markers) //displays the markers array properly
for(var i = 0; i < this.markers.length; i++)
{
this.markers[i].addListener("click",this.markerClicked, this);
}
}
markerClicked(marker) //the clicked marker is passed
{
console.log(this.markers);
//here is the problem. The console says that the markers array is empty
//when called from this function
}
}
完美的工作!还有一个额外的问题:是否有任何方法可以确定数组中的哪一个标记实际上已被点击?我试图将'i'索引传递给箭头函数,但是我无法让它工作。任何其他想法? –
如果您想要保持与GMaps API内联,您必须将另一个事件侦听器附加到标记本身,即'marker.addListener('click',()=> {...})''。然后,如果需要,可以在箭头函数内重复使用'marker'变量。 – AngularChef