Sarah Mandana
Sarah Mandana

Reputation: 1513

Cannot read properties of undefined for service error when passing method as parameter from service

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

}

Upvotes: 1

Views: 541

Answers (1)

Alexis Deprez
Alexis Deprez

Reputation: 575

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

Upvotes: 1

Related Questions