RxJs Subject.subscribe method not working as expected

眉间皱痕 提交于 2019-11-28 09:31:50

问题


Subject.subscribe 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 (angular2.dev.js:1), <anonymous>:29:29)
at ChangeDetector_AppComponent_0.AbstractChangeDetector.handleEvent (angular2.dev.js:8788)
at AppView.dispatchEvent (angular2.dev.js:9396)
at AppView.dispatchRenderEvent (angular2.dev.js:9391)
at DefaultRenderView.dispatchRenderEvent (angular2.dev.js:7819)
at eventDispatcher (angular2.dev.js:9781)

See Plunkr here.


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

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


回答1:


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: https://plnkr.co/edit/6M1lPLZA16vwQsVAjNzc?p=preview

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



来源:https://stackoverflow.com/questions/40361623/rxjs-subject-subscribe-method-not-working-as-expected

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