angular: rxjs/BehaviorSubject with rxjs/Subscription not working between two components unless its a child component

using rxjs/BehaviorSubject and rxjs/Subscription to communicate two components through a service like this:

Service (code related to the problem):

import { BehaviorSubject } from 'rxjs/BehaviorSubject'

private _clientModalActionSource = new BehaviorSubject<string>('')
modalAction$ = this._clientModalActionSource.asObservable()
public updateClientModalAction(action) {
   this._clientModalActionSource.next(action)
   console.log('sent')
}

Component A :

this._api.updateClientModalAction(id)

Component B :

import { Subscription } from 'rxjs/subscription'

private _subscription: Subscription
ngOnInit() { this._subscription = this._api.modalAction$.subscribe(res => {
   this.refreshModal(res)
   console.log('received')
})}

This is working perfectly if Component B is child of Component A, but if A is the root component and B is inside its <router-outlet> (or the opposite) nothing is being received to the subscription, I only get sent in the console. (without ‘received’)

Plunker

so unless I’m doing something wrong…

I’m submitting a … (check one with “x”)

[x ] bug report 

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 16 (4 by maintainers)

Most upvoted comments

In order two share a service between multiple components, you should provide the service at a level higher and not add the service to the providers of both components.

https://plnkr.co/edit/aX8HTN3F7LJHLjYo5YiK?p=preview

I wasted literally 2 days on that thing. It’s absolutely not clear for anyone starting with Angular2 that a service registered at a child component will shadow the rest of the app from the events emitted there. The quickstart registers the HeroService at the HeroComponent. That put me on the wrong track. I simply changed the app and added the HeroService in the root module while experimenting. That’s where the mess started. A sentence like “Do not register any provider twice as this will create two independent instances.” might have helped me in the quickstart chapter “When to use the NgModule and when an application component?”

5 hours banging my head against the wall with this (it even made me miss $rootScope)… the solution as pointed out by @brandonroberts took 30 seconds…

Please add a plunker with a minimal repro. Thanks.