wolfhoundjesse wolfhoundjesse - 3 months ago 12
TypeScript Question

I need help understanding RxJx subscribe syntax

This is what I am doing now, and I wonder if there is a better way

this.dataService.subscribe(
data => this.data = data,
error => alert('Something went wrong'),
() => this.doSomethingOnCompletion());


If I'm not catching data, however, I might just alter the first of the three functions:

() => null,


The documentation for rxjs 4.x doesn't answer this question well enough for me. Version 5.x explains even less.

So, what is the verdict? Is the following wrong when I need to do nothing more than trigger something to happen?

this.dataService.subscribe(
() => null,
error => alert('Boom.'),
() => this.doSomethingOnCompletion());


If I didn't need to do something on completion, I'd just leave that part out. What if I only wanted to check for errors and nothing else?

Answer

RxJS 4 if you only need errors then you can use the subscribeOnError method which handles only the errors.

You can use the subscribe method as well, but you just need to pass a null value for the handlers you don't want, you don't have to pass your own noop.

this.dataService.subscribe(
    null,
    error => alert('Something went wrong'));

RxJS 5 you can pass a so-called PartialObserver:

this.dataService.subscribe({
  error: error => alert('Boom.'), 
  complete: () => this.doSomethingOnCompletion()
})