Search code examples
typescriptngrxangular9

typescript field is null when passing a private method to a lambda


I have the following class; i made it as short as possible to explain the issue:

@Injectable()
export class TestService {
...

  private testSubscription: Subscription = new Subscription;

  constructor(
    private store: Store<FromTest.IState>,
    private otherService: otherService) {
  }

  public MainTestMethod() {
       this.testSubscription = this.otherService.getSomethingObservable().subscribe(toBeCalledTestMethod)
  }

  private toBeCalledTestMethod(something: boolean) {
       this.store <- undefined
  }
...
}

When passing a method to subscribe the field "store" is undefined. However when i change the subscribe method to:

   this.testSubscription = this.otherService.getSomethingObservable().subscribe(x => toBeCalledTestMethod(x))

the field "store" has a value (which is expected).

Glad i found a way to get it working but i don't understand why passing the method as a lambda would cause different behavior.

I'm new to typescript and angular so would like to learn why.

Thanks in advance!


Solution

  • Thanks to @ritaj for commenting "toBeCalledTestMethod.bind(this)" i now know why.

    Passing the method like this:

    this.otherService.getSomethingObservable().subscribe(toBeCalledTestMethod)

    Passes the method without its context to the subscribe function.

    To keep the context with the method you either bind it to the class with bind or use a lambda to retain your context.

    As passing a lambda will pass a function which will execute the method in it's context.