首页 > 解决方案 > 如何在angular8中取消订阅行为主题

问题描述

嗨,我正在使用 Angular8 应用程序,其中我使用了 Replay 主题和 Behavior 主题,对于初始点击它只点击 api 1 次,但是如果我在选项卡之间切换,订阅点击 fr 多次,如果我点击了选项卡3 次,API 被点击了 6 次,所以它开始成倍增加,有没有办法取消订阅行为主题,我希望 API 只点击一次,我尝试取消订阅,但它没有工作。

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>

其他组件:

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

演示

标签: angularbehaviorsubjectreplaysubject

解决方案


在您订阅的其他组件中,您必须记住取消订阅。否则您可能会遇到内存泄漏问题等。

所以在你有订阅的地方,记得取消订阅。

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

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

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

推荐阅读