简体   繁体   English

RxJS-可观察的模块-抛出未定义

[英]RxJS - Observable Modules - throw undefined

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. 但是由于某种原因, throw是不确定的。 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 rxjs@5.0.0-beta.6 combined with angular@2.0.0-rc.4 for Ionic 2. 我正在将rxjs@5.0.0-beta.6与angular@2.0.0-rc.4结合用于Ionic 2。

Observers (which have been renamed "Subscribers" in RxJS v5, FYI) don't have a method called throw() . 观察者(在RxJS v5中已重命名为“订阅者”,FYI)没有称为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). 您正在混合使用Observables(定义序列和这些序列上的运算符)和Subscriber / Observers(仅接收来自Observable的下一条/错误/完成消息)。

What you want is an Observable that just emits an error object. 您想要的是一个Observable,它仅发出一个错误对象。 Then, any Subscriber/Observer subscribing to it will get an .error() notification. 然后,任何订阅它的订户/观察者将收到一个.error()通知。 So, instead of using Observable.create() , use Observable.throw(new Error('Test')) . 因此,不要使用Observable.create() ,而要使用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. 与使用Observable.create(observer => ...)和调用observer.error(...) ,此方法还更健壮,因为可以保证生成的Observable遵守Rx合同。 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. 如果使用.create() ,则必须手动执行类似操作,确保在错误发生后不再发出进一步的通知,确保Observable的所有后续订阅者都立即收到错误通知,等等。使用Observable.throw(...) ,这一切都会自动为您解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM