Angular 2: Observable / Subscription not triggering

吃可爱长大的小学妹 提交于 2019-11-30 17:22:24

I think the issue is your Subject type With Subject, any component that subscribes after an event has fired will NOT receive a value. To replay the previous value to late subscribers use BehaviorSubject or ReplaySubject instead of Subject.

More on different Subject types from http://reactivex.io/documentation/subject.html

Behavior Subject

When an observer subscribes to a BehaviorSubject, it begins by emitting the item most recently emitted by the source Observable (or a seed/default value if none has yet been emitted) and then continues to emit any other items emitted later by the source Observable(s).

ReplaySubject

ReplaySubject emits to any observer all of the items that were emitted by the source Observable(s), regardless of when the observer subscribes.

A BehaviorSubject does require a default value when setting it up. So you'd need to create it with some sort of value:

updateIBOsNavigationSubject = new BehaviorSubject<any>('');
updateIBOsNavigation$ = this.updateIBOsNavigationSubject.asObservable();

updateIBOsNavigation(navigationData) {
    log.d('updateIBOsNavigation', JSON.stringify(navigationData));
    this.updateIBOsNavigationSubject.next(navigationData);
}

A ReplaySubject does not require a default value.

EDIT

When using a shared service it is also important to make sure the service is being provided ONLY at the root module. If it is provided multiple places, then the components may not be getting the same instance. Even if the service is provided at the root level, if a module between the root level and your component provides the service, a new instance will get sent down that branch of the Dependency Injection tree.

Hope this helps.

When we include a service in 'providers', then it is instantiated and this state is maintained between its component as well as its child components.

And, if we include the service in both components provider array, then it is no more following singleton. The state will be independent and not shared between them.

So, include your service only at parent component or your root component.

I too faced this issue and solved with help of this solution here, https://stackoverflow.com/a/38034298/5730167.

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