Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 + RxJS BehaviorSubject subscription not working on all components

I'm trying to make some sort of communication between my components, so I'm using a service with a BehaviorSubject and Subscription in the components 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.

what am I doing wrong?

like image 467
Motassem MK Avatar asked Nov 27 '22 02:11

Motassem MK


1 Answers

well the problem was simpler than I thought, I was not using the service on a higher level, I shouldn't have used providers: [ApiService] in each component, instead it should be only on the higher root component.

I hope this will help someone.

https://github.com/angular/angular/issues/11618#event-790191142

like image 146
Motassem MK Avatar answered Dec 05 '22 15:12

Motassem MK