user7629970
user7629970

Reputation: 91

Why does typescript not see my function?

I have the following Listener that is in a onInit method:

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

Outside I have a method which is called when the event is triggered, Angular2 compiles this fine but when I try activate the event by clicking when running the app I get a error saying

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

Upvotes: 1

Views: 71

Answers (1)

eko
eko

Reputation: 40647

Change

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

with

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

your this is not refering to your component.

Alternatively, the old js way:

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

I suggest you to read this for a more in-depth answer: How to access the correct `this` inside a callback?

Upvotes: 4

Related Questions