Reputation: 6242
I am trying to throw an error within an observable with the simple bit of code:
return Observable.create((observer) => {
observer.throw(new Error('Test'));
});
Yet for some reason, throw
is undefined. I have no idea why at the top of my class, I have the following import:
import 'rxjs/observable/throw';
I have also tried:
import 'rxjs/Observable/throw';
and:
import 'rxjs/add/observable/throw';
Yet none are working? Am I missing a trick?
I am using [email protected] combined with [email protected] for Ionic 2.
Upvotes: 0
Views: 1120
Reputation: 461
Observers (which have been renamed "Subscribers" in RxJS v5, FYI) don't have a method called throw()
. You're mixing up Observables (which define sequence and operators on those sequences), and Subscribers/Observers (which just receive next/error/complete messages from an Observable).
What you want is an Observable that just emits an error object. Then, any Subscriber/Observer subscribing to it will get an .error()
notification. So, instead of using Observable.create()
, use Observable.throw(new Error('Test'))
.
This method is also more robust than using Observable.create(observer => ...)
and calling observer.error(...)
, because the resulting Observable is guaranteed to uphold the Rx contract. If you were using .create()
, you have to manually do things like, ensure that no further notifications are emitted after the error, that all subsequent subscribers to the Observable immediately get an error notification, etc. With Observable.throw(...)
, that's all taken care of for you, automatically.
Upvotes: 2