method VS () => method() - Angular 2 done() callback function subscribe Observable RxJS

1.9k views Asked by At

I have a question about done function in subscribe() method when using RxJS.

My application has a code:

ngOnInit() {
  this._dictionaryService.loadDictionary()
  .subscribe(
    dictionary => this.dictionary = dictionary,
    error => this.errorMessage = <any>error,
    this.loadQuestion);
}

and it doesn't work. But if a change

this.loadQuestion);

to

() => this.loadQuestion());

it works ok.

so, this code:

ngOnInit() {
  this._dictionaryService.loadDictionary()
  .subscribe(
    dictionary => this.dictionary = dictionary,
    error => this.errorMessage = <any>error,
    () => this.loadQuestion());
}

works well.

this._dictionaryService.loadDictionary() gets JSON data from file.

this.dictionary is a class property. When I try to assess this property in 1st example, i get an undefined. But in 2ns example everything is ok.

So, it works, but I don't understand the difference. I don't understand why 1s example doesn't work.

Could somebody explain me this, please?

1

There are 1 answers

0
Miguel Ventura On BEST ANSWER

That's because when you write this.loadQuestion you're passing a reference to the function loadQuestion but you'll be losing the this context. When you use the arrow function, the this context will be kept.

You could also write this.loadQuestion.bind(this) to obtain a loadQuestion function with the this context fixed to the current one.