I am having some troubles working with BehaviorSubject.
In my app I have a banner with 3 tabs which you can select. Each one will show different contents.
So for get in other component the tab selected, I decided to use BehaviorSubject, which in theory will update the value of tabSelected.
So in my banner component I have:
component.html:
<div *ngFor="let tab of tabs">
<div class="tab btn-tab" (click)="setTabSelected(tab)">
</div>
</div>
component.ts
ngOnInit() {
this.setTabSelected(this.tabs[0]);
}
setTabSelected(tab) {
this.shareDataSv.sendTab(tab);
}
In my intermediary service I have:
private tabSubject = new BehaviorSubject(new TabsValues());
tab$ = this.tabSubject.asObservable();
sendTab(tab: TabsValues) {
console.log('Send tab', tab);
this.tabSubject.next(tab);
}
And in the component that will receive the selected tab:
reciver.component.ts
ngOnInit() {
this.knowSelectedTab();
}
knowSelectedTab() {
this.shareDataSv.tab$.subscribe(data => this.tab = data);
console.log('Selected tab', this.tab);
}
So at the beginning I obtain perfectly the value of the predefined tab. But when I click to other tab, I see in the service that is sending the new value, but I don't obtain any data in the subscription.
I leave here the example: stackblitz example
Any clue what can I do? Thank you!
P.D.: If I use an interval for knowSelectedTab(), I am able to see the changes.