tMJ tMJ - 11 months ago 79
TypeScript Question

RxJs Subject.subscribe method not working as expected

method when called outputs the following error:

TypeError: Cannot read property '_subscribe' of undefined
at BidirectionalSubject._subscribe (Rx.js:10239)
at BidirectionalSubject._subscribe (Rx.js:10239)
at BidirectionalSubject.Observable.subscribe (Rx.js:9924)
at AppComponent.doIt (app.component.ts:32)
at ChangeDetector_AppComponent_0.handleEventInternal (eval at ChangeDetectorJITGenerator.generate (, <anonymous>:29:29)
at ChangeDetector_AppComponent_0.AbstractChangeDetector.handleEvent (
at AppView.dispatchEvent (
at AppView.dispatchRenderEvent (
at DefaultRenderView.dispatchRenderEvent (
at eventDispatcher (

See Plunkr here.

This is a part of a bigger problem I am facing. In my actual code, the
method does not throw but it simply does not add an
to the
, and hence on all
invocations no one receives the emitted data.

I think the problems are related. In my actual code I am using version
of rxjs. In the plukr though, the
dependency seems to be coming from angular itself.

Answer Source

Be aware of using Subject.create().

This is not the same as new Subject() and absolutely most of the time you want to use just new Subject() instead of Subject.create(). With Subject.create() you're creating an instance of AnonymousSubject which never subscribes itself and therefore the flatMap() operator throws an error when trying to subscribe AnonymousSubject to another AnonymousSubject.

See my answer to a similar question: Subjects created with Subject.create can't unsubscribe.

I just changed Subject.create() to new Subject() and it's probably working.

See your updated demo:

Although, I don't know what's that demo supposed to do so I can't tell whether it's working correctly.