问题
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