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();
}
CodePudding user response:
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)();
}