1

I've created a simple pointer to a method like so:

export class SmbwaService {
    getExistingArsByLab(labId: number): Observable<SmwbaAr[]> {
        this.otherMethod();
    }

    otherMethod(): void {
    }
}


let method: (x: number) => Observable<SmbwaAr[]>;
method = this.service.getExistingArsByLab;
method(12);

That executes OK insofar as it does call getExistingArsByLab method. However, I then get an error when it tries to call otherMethod because:

Cannot read property otherMethod of undefined.

What's the right way to do this? Obviously in my actual code method is being set to one of a number of different methods based on some conditions.

Gargoyle
  • 9,590
  • 16
  • 80
  • 145

1 Answers1

2

Use Function.bind to obtain a function reference that's bound to a particular value of this:

method = this.service.getExistingArsByLab.bind(this.service)
method(2)
jspcal
  • 50,847
  • 7
  • 72
  • 76