Arm144
Arm144

Reputation: 773

Subscribe to BehaviorSubject

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.

Upvotes: 1

Views: 1005

Answers (1)

AVJT82
AVJT82

Reputation: 73337

You are instantly unsubscribing, so the subscription ends there. You should unsubscribe to observables, but do it in OnDestroy. So remove the unsubscribe:

knowTab() {
  this.subscription = this.shareDataSv.tab$.subscribe(data => {
    if (data) {
      this.tab = data;
      console.log('Obatined data',this.tab);
    }
  });
  // remove this!
  // this.subscription.unsubscribe();
}

// add this
ngOnDestroy() {
  this.subscription.unsubscribe();
}

Your forked STACKBLITZ

Upvotes: 3

Related Questions