0

I have a code like this:

myMethod(data: any, layerId: string, dataSubstrings): void {
    someObject.on('click', function(e) {
        this.api.getSomething(a).subscribe((result: any) => { // WRONG CALL 1. It is from another component
            // code
            this.outSideMethod(a)); // WRONG CALL 2

            }
        }, (error: any) => {
            return {};
        })
    });


outSideMethod(a): any[] {
    //etc
}

I need to call this.api.getSomething(a)); (and also outSideMethod()) but I get `Cannot read property 'getSomething' of undefined.

I don't know my problem using this (POO), could someone give me some hints please.

pmiranda
  • 7,602
  • 14
  • 72
  • 155

2 Answers2

1

Your context object (the one pointed by the keyword this) has no api property set, so you cannot execute the getSomething method.

Check the logic about the 'this' keyword behaviour https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this because it depends on the way to invoke the method.

In angular, if you are injecting this dependency add the scope modifier (private for example) to the parameter of the constructor to bind to an internal property so you can access to it with 'this'

Andoni
  • 171
  • 9
-1

try changing the function to lamda expression .

someObject.on('click', function(e) {} )

to

someObject.on('click', (e) =>{});

Vishnu
  • 897
  • 6
  • 13