I am new to rxjs, so I would like to ask a question regarding Angular 2
, Observables
and BehaviorSubject/Subject
.
So, what I want to achieve is : onclick
of a button
inside a ComponentA
to notify other components for example ComponentB
, ComponentC
.
What I did so far is to create a service
:
private isMenuOpenBS = new BehaviorSubject(false);
toggleMenu(): void {
this.isMenuOpenBS.next(!this.isMenuOpenBS.getValue());
}
getMenuState(): Observable<boolean> {
return this.isMenuOpenBS.asObservable();
}
Then having one component with provide menuService
is calling the this.menuService.toggleMenu()
which changes the value of the BehaviorSubject
. Code :
toggleMenu(): void {
this.menuService.toggleMenu();
this.menuService.isMenuOpenBS.subscribe(
(data) => {
console.log(data)
},
(e) => {console.log(e)},
() => {console.log('completed')}
)
}
And another component that OnInit()
subscribes
to the getMenuState()
which is an Observable
, but it get's values only on OnInit()
. Code:
ngOnInit(): void {
this.menuService.getMenuState().subscribe(
(data)=>{
this.messages = data;
console.log('nav component');
},
(e) => {console.log(e)},
() => {console.log('completed')}
)
}
The complete
function is never called.
Any ideas what am I doing wrong or if i am missing something in the logic ?
--
Edit : So, to explain a bit more the problem was that I could see the first value that the observable had oninit but nothing else. No error no complete after that or no "next" value which was wrong since I was sending new values from the subject. In the end the problem was with the provider list of the components and not a problem of observables or subjects, but before solving the problem it wasn't easy to see that the problem was there.