Angular2:失去对observable的访问权限

时间:2017-01-19 18:08:48

标签: angular typescript ionic-framework

我有一个离子/角度2应用运行。有一个谷歌地图加载到视图中。我有一个名为markers的可观察对象,它是一个谷歌地图标记对象数组。我将它们推送到数组以使它们出现在地图上。然后,我将事件监听器添加到所有标记。点击功能正常,但我无法访问this.markers。为什么会这样?也许更好的问题是如何创建一个可在整个班级访问的普通变量?

这是我的代码:

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

1 个答案:

答案 0 :(得分:1)

看起来是因为当您调用回调this.markerClicked时,它不再绑定到该类,因此无法再访问this.markers

我看到两个选项:

1)内联你的回调并使用箭头函数声明它(箭头函数保留this的上下文)

this.markers[i].addListener("click", (marker) => {
  // do something with marker and this.markers
  console.log(this.markers);
}, this);

2)似乎有些hackish但是......你有没有尝试将你的回调绑定到班级?

类似this.markerClicked.bind(this)而非this.markerClicked