0

Coming from another question, while doing a demo I found a strange bug that I fixed by pure chance.

  private updateCurrentCharacter() : void {
    this.fetchCharacter(this.currentCharacter)
      .subscribe( 
        character => this.characterSubject.next(character)
      );
  }

This code will work, but

  private updateCurrentCharacter() : void {
    this.fetchCharacter(this.currentCharacter)
      .subscribe( 
        this.characterSubject.next
      );
  }

But this one wont, with Angular throwing the following error: General error observers is undefined

Anyone has any idea why is that? From my understanding, subscribe is a lazy operation, and both codes are idempotent.

You can try it on this demo: Demo

JoshiRaez
  • 97
  • 8
  • 1
    TLDR; When doing `this.characterSubject.next` you are loosing context in `next`. So you need to either use arrow function or `this.characterSubject.next.bind(this.characterSubject)` – Yury Tarabanko Aug 13 '20 at 12:35
  • Alright, so When using arrow function, because the arrow function is created like any other value, the second code becomes something like arrowFunction = objectInstance.subject.next .subscribe(arrowFunction) But without arrow function, the execution of that code when subscribe is defined will set this to the global object, hence the need to bind it to the object instance. Alright, thanks! Put it as an answer so I can accept it – JoshiRaez Aug 13 '20 at 12:40

0 Answers0