7

I am new to Angular 2. I wrote below code in Angular

export class TestClass {

    constructor() {
        this.initMap();
    }

    initMap() {
        this.marker.addListener('dragend', this.onMarkerDrop);
    }

    onMarkerDrop(event) {
        this.functionTwo(); // Getting error this.functionTwo is not a function
    }

    functionTwo() {

    }
}

Note: Before asking this question I searched in stackoverflow I got these links

'this.function' is not a function - OO JS

this.function is not a function :typescript

Angular - this.function is not a function

They are saying that use Arrow functions to call other member functions. But I don't know how to implement their suggestions in my code. Might I didn't understood them correctly.

I want help from you like, how to call this.functionTwo() using arrow function from functionOne();

Thank you for your help.

Sivakumar Tadisetti
  • 4,865
  • 7
  • 34
  • 56

2 Answers2

6

As per your code updation , you can use it like :

this.marker.addListener('dragend', this.onMarkerDrop.bind(this));
// OR
this.marker.addListener('dragend', ($event) => this.onMarkerDrop($event));

Your code will work 100% fine : (Before Question Updated)

functionOne() {
    this.functionTwo(); // Getting error this.functionTwo is not a function
}

functionTwo() {
    alert('function2');
}

Please check the below code for more clarification

functionOne() {
    // this will throw error this.functionTwo is not a function
    setTimeout(function(){ // normal function
        this.functionTwo();  
    })

    // This wont throw the error
    setTimeout(() => { // fat arrow
        this.functionTwo(); // Getting error this.functionTwo is not a function        
    })
}

functionTwo() {
    alert('function2');
}

Why it will work with fat arrow :

this is picked up from surroundings (lexical). Therefore, you don’t need bind() or that = this, anymore.

With Normal function you need to do bind() or that = this

Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122
2

Your function onMarkerDrop is passed as a callback where the context will change and this will have a different value. Use arrow or bind while sending to preserve context.

this.marker.addListener('dragend', this.onMarkerDrop.bind(this));

or

this.marker.addListener('dragend', ($event)=>this.onMarkerDrop($event));
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103