How to unsubscribe behaviour subject in angular8

284 Views Asked by At

Hi i am using Angular8 application, in which i have used Replay subject and Behaviour subject, for the initial click it hits the api for only 1 time, but if i change between tabs, the subscription hits fr multiple times, if i have clicked tab for 3 times, the API gets hitted for 6 times, so it starts multiplying, is there any way to unsubscribe the behavious subject, i want the API to hit only one time, i tried with unsubscribing, but it didnt work.

TS: App.component.ts:

_otherTab: ReplaySubject<any> = new ReplaySubject();

  other() {
      this.othertab = 2;
      this._otherTab.next(2); 
  }

HTML:

  <div class="card-header bg-dark border-bottom-0">
                    <ul class="nav nav-tabs nav-fill card-header-tabs" id="" role="tablist">
                        <li class="nav-item">
                            <a class="nav-link active" data-toggle="tab" href="#basic" role="tab">User</a>
                        </li>
                        <li class="nav-item" (click)="other()">
                            <a data-toggle="tab" href="#eo" role="tab" 
                            [ngClass]=" {'nav-link':(true),'disabled' : (_otherTabEnabled === false) }" >Other</a>
                        </li>
                    </ul>
                </div>

  <div class="tab-pane" id="eo" role="tabpanel">
   <app-other-table [othertab]="_otherTab"></app-other-table>
   </div>

Other Component:

 @Input() othertab: BehaviorSubject<any>;
     ngOnInit() {
        this.othertab.subscribe(val => {
          if (val) {
            this.showTab = true;
          }
        });
      }

Demo

1

There are 1 best solutions below

9
On

in your Other component, where you subscribe, you must remember to unsubscribe. Otherwise you can have memory leak issues etc.

So where you have the subscribe, remember to unsubscribe.

 subs;
 @Input() othertab: BehaviorSubject<any>;

     ngOnInit() {
        this.subs = this.othertab.subscribe(val => {
          if (val) {
            this.showTab = true;
          }
        });
      }

    ngOnDestroy(){
        this.subs.unsubscribe();
    }