1

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.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Arm144
  • 721
  • 1
  • 10
  • 23
  • 1
    This is asynchronous. Your console log is outside subscription, so it won't console log again. Add the console log inside the subscription and it should fire. Also remember to unsubscribe to the observables. – AT82 Sep 12 '19 at 10:50
  • 1st of all, this question is not duplicated. 2nd, the problem is the subscription is not being fired if you read the full question with and interval i see the log – Arm144 Sep 12 '19 at 10:55
  • fair enough. so it didn't solve your issue to change the placement of console log? If not, please provide a [mcve], best would be a stackblitz. This is not currently. Imagine if we were to put this code in a stackblitz, would it compile? No, because this is not reproducible currently, not enough code. – AT82 Sep 12 '19 at 11:02
  • @AJT_82 here is the [example](https://stackblitz.com/edit/angular-ewh3u9) – Arm144 Sep 12 '19 at 11:27

1 Answers1

2

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

AT82
  • 71,416
  • 24
  • 140
  • 167