繁体   English   中英

如何在方法中取消订阅 function?

[英]how to unsubscribe of function in method?

使用 angular js 处理对话框组件,现在我发现我的 function 已订阅,并且在 if 条件下不退出方法,但继续执行另一个afterClosed()代码示例:

openCreateNewContentDialog(): void {
    const oldData = this.dataSource.data;
    const dialogConfig = AppConstants.matDialogConfig();
    const dialog = this.dialog.open(LicenseDialogComponent, dialogConfig);

    dialog.beforeClosed().subscribe(licenceDate => {
      for (const datesToCheck of oldData) {
        const newDateFrom = new Date(licenceDate.expirationDateFrom);
        const oldDateTo = new Date(datesToCheck.expirationDateTo.toString());
        if (newDateFrom <= oldDateTo) {
          // console.log('return?');
          return;
        }
      }
    });

    dialog.afterClosed().subscribe(licence => {
      if (licence) {
        this._value.push(licence);
        this.dataSource.data = this.value;
        this.change();
      }
    });
  }

取消订阅beforeClosed() function 的最佳和优化方法是什么?

因此,根据您的描述,我知道t want a second subscription to happen if the condition in the first subscriber is true, right? But you subscription will happen anyway because you instantiated it in the method, the code in the subscribe() it's just a callback. So if you don t want a second subscription to happen if the condition in the first subscriber is true, right? But you subscription will happen anyway because you instantiated it in the method, the code in the subscribe() it's just a callback. So if you don t want a second subscription to happen if the condition in the first subscriber is true, right? But you subscription will happen anyway because you instantiated it in the method, the code in the subscribe() it's just a callback. So if you don不想进行大量重写,我建议将订阅存储在变量中,这样您就可以访问它们并且可以随时取消订阅。

openCreateNewContentDialog(): void {
const oldData = this.dataSource.data;
const dialogConfig = AppConstants.matDialogConfig();
const dialog = this.dialog.open(LicenseDialogComponent, dialogConfig);

const beforeClosed = dialog.beforeClosed().subscribe(licenceDate => {
  for (const datesToCheck of oldData) {
    const newDateFrom = new Date(licenceDate.expirationDateFrom);
    const oldDateTo = new Date(datesToCheck.expirationDateTo.toString());
    if (newDateFrom <= oldDateTo) {
      // console.log('return?');
      afterClosed.unsubscribe();
      return;
    }
  }
});

const afterClosed = dialog.afterClosed().subscribe(licence => {
  if (licence) {
    this._value.push(licence);
    this.dataSource.data = this.value;
    this.change();
  }
});

}

我希望它有帮助! 如果您必须处理多个订阅,您也可以尝试https://www.digitalocean.com/community/tutorials/angular-takeuntil-rxjs-unsubscribe

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM