2017-04-11 63 views
1

我有以下的监听器是在OnInit方法:在运行时为什么打字稿看不到我的功能?

google.maps.event.addListener(this.map, 'click', function(event) { 
     console.log(event.latLng); 
     var lt = event.latLng.lat; 
     var ln = event.latLng.lng; 
     console.log(lt()); 
     console.log(ln()); 
     this.onStoreMarker(lt(),ln()); 
    }); 

外面我有一个在触发事件被称为方法,Angular2编译这很好,但是当我试图通过单击激活事件该应用程序我得到一个错误说

Uncaught TypeError: this.onStoreMarker is not a function

onStoreMarker(lt: number,ln: number) { 
     var newStore = prompt("Please enter your store name", "Store Name"); 
     var location = {lat: lt, lng: ln}; 
     var marker = new google.maps.Marker({ 
      position: location, 
      map: this.map, 
      title: newStore, 
     }); 
    } 

回答

4

变化

google.maps.event.addListener(this.map, 'click', function(event) { 

google.maps.event.addListener(this.map, 'click', (event)=> { 

this不是指的你的组件。

另外,老JS方式:

var self = this; // store this in a variable to use it later 
google.maps.event.addListener(this.map, 'click', function(event) { 
     console.log(event.latLng); 
     var lt = event.latLng.lat; 
     var ln = event.latLng.lng; 
     console.log(lt()); 
     console.log(ln()); 
     self.onStoreMarker(lt(),ln()); // <-- use it later 
    }); 

我建议你阅读此进行了较深入的答案:How to access the correct `this` inside a callback?

+1

由于它的工作 – user7629970