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?
That's because when you write
this.loadQuestion
you're passing a reference to the functionloadQuestion
but you'll be losing thethis
context. When you use the arrow function, thethis
context will be kept.You could also write
this.loadQuestion.bind(this)
to obtain aloadQuestion
function with the this context fixed to the current one.