1

I have to pass a function of service as a parameter to another function. Whenever, I try to pass function as parameter and it executes, then I get error 'Cannot read properties of undefined myService'

When I call this.myService.method() individually. It's completely working fine. There is no problem. What could be the issue?

My ts file:

constructor(private myService: MyService)

 function1(): void {
        this.function2(this.myService.method)
    } 

function2(f: Function)
{
    f();

}
Sarah Mandana
  • 1,474
  • 17
  • 43
  • Does this answer your question? [How does the "this" keyword work, and when should it be used?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work-and-when-should-it-be-used) – Yury Tarabanko Jan 12 '23 at 21:59

1 Answers1

1

Full details : How does the "this" keyword work, and when should it be used?

Solution 1 : bind this to service context on initialization

function1(): void {
    this.function2(this.myService.method.bind(this));
    //or this.function2(() => this.myService.method());
} 

Solution 2 : bind this to service context before call

function2(f: Function)
{
    f.bind(this)();
}
Alexis Deprez
  • 550
  • 2
  • 12