How to transform a Subject into an Observable in RxJs 5

冷暖自知 提交于 2019-12-10 16:38:22

问题


How can we transform a Subject into an Observable in RxJs 5 ? This functionality is useful for example when we want to expose the Subject for subscription but don't want to yield control of calling next() on it, and prefer to keep the issuing of new values private.

The docs (see here) mention something like this:

var subject = new Rx.Subject();

var obs = subject.asObservable();

But in RxJs 5 this currently does not work (alpha 8), we get the following error:

"TypeError: subject.asObservable is not a function

回答1:


RxJS 5 is a rewrite (currently in beta) and has lots of renamed/removed methods, among other changes. One of the removed ones is asObservable.

You can get the same functionality by creating an observable with the private subject's subscribe function:

const subj = new rx.Subject();
const exposed = new rx.Observable(fn => subj.subscribe(fn));



回答2:


FYI: Subject.prototype.asObservable() will be in the next release 5.0.0-beta.2.

At that point, you can just call mySubject.asObservable().



来源:https://stackoverflow.com/questions/35094705/how-to-transform-a-subject-into-an-observable-in-rxjs-5

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!