执行事件时如何防止订阅创建的内存泄漏?

How to prevent memory leak of subscriptions creation when perform an event?

我需要确保有一个订阅(例如在构造函数中)并将事件流从另一个组件链接到该组件的可观察 属性。

我写的代码并没有防止内存泄漏,而是在每个事件中创建一个新的订阅。

图片组件ts

export class ImagePanelComponent{
   constructor(
    private servicee: service,
    private status: status,
  ) {
  }

  updatePage(viewerPage: number){
    this.service.pages$.pipe(take(1)).subscribe(
      (pages) => this.status.updatePage$.next(pages[viewerPage - 1]),
    );
  }
}

图片组件HTML

<x-panel>
  <div content>
        <osd-component
            *ngIf="viewerData"
            [viewerData]="viewerData"
            [page]="pageNumber"
            (pageChange)="updatePage($event)">
        </osd-component>
        <p *ngIf="!viewerData">Found no source file</p>
  </div>
</x-panel>

创建一个 BehaviorSubect 来跟踪 pageChange 事件排放应该适用于此。

类似于:

export class ImagePanelComponent{
   constructor(
    private servicee: service,
    private status: status,
  ) {
     this._setSubscriptions();
  }

  private pages$ = new BehaviorSubject(0);

  updatePage(viewerPage: number){
    this.pages$.next(viewerPage);
  }
  
  _setSubscriptions() {
    // Here is your subscription to pages$ where you'll call your service to update the page number.
    // Note: You'll need to handle your unsubscribe logic (this.unsubscribe) 
    this.pages$.pipe(takeUntil(this.unsubscribe)).subscribe(
      (page) => this.service.SomeUpdatePageMethod(pages[page - 1])
    );
  }

}