取消订阅

时间:2020-05-19 07:37:29

标签: javascript angular ag-grid

在对话框的closeAll方法之后如何取消订阅该功能?是否可以将订阅转换为变量,然后以某种方式将其应用于“ onProjectAdded”实例?

    this.dialog
      .open(GridAddDialogComponent)
      .componentInstance.onProjectAdded.subscribe((projectData) => {
        this._gridApi.setRowData([...this.rowData1, projectData]);
      })
      this.dialog.closeAll()
  }

1 个答案:

答案 0 :(得分:0)

有2种方法: 1.组件销毁后自动退订:

export class ExampleComponentComponent implements OnInit, OnDestroy {

  readonly _destroy$: ReplaySubject<boolean> = new ReplaySubject<boolean>(1);

  constructor(
    private readonly dialog: MatDialog
  ) { }

  ngOnInit() {
    this.dialog
      .open(GridAddDialogComponent)
      .componentInstance.onProjectAdded
      .pipe(takeUntil(this._destroy$))
      .subscribe((projectData) => {
        this._gridApi.setRowData([...this.rowData1, projectData]);
      })
      this.dialog.closeAll();
  }


  ngOnDestroy(): void {
    this._destroy$.next(null);
    this._destroy$.complete();
  }

}
  1. 在需要时退订(在我的情况下,为摧毁组件,但您可以在任何地方都可以这样做):

导出类ExampleComponentComponent实现OnInit,OnDestroy {

  public subscriptions: Subscription[] = [];

  constructor(
    private readonly dialog: MatDialog
  ) { }

  ngOnInit() {
    const subscription = this.dialog
      .open(GridAddDialogComponent)
      .componentInstance.onProjectAdded
      .subscribe((projectData) => {
        this._gridApi.setRowData([...this.rowData1, projectData]);
      });
    this.subscriptions.push(subscription);
    this.dialog.closeAll();
  }


  ngOnDestroy(): void {
    this.subscriptions.forEach((sub) => sub.unsubscribe());
  }

}

此外,您可以使用单次订阅而不是它的数组。