Angular - 使用函数手动销毁组件

Angular - Destroy component manually using function

我有一个组件 (RecordPage) 是使用静态函数从另一个组件创建的:

static openRecordPage(drawerService: NzDrawerService, args: RecordPageArgs) {
    const drawerRef = drawerService.create<RecordPageComponent>({
      nzTitle: args.drawerTitle,
      nzWrapClassName: 'drawer-size-4x drawer-body-no-padding',
      nzContent: RecordPageComponent,
      nzContentParams: {
        moduleId: args.moduleId,
        sourceObject: args.sourceModuleId,
        moduleActionType: args.moduleActionType,
        sourceObjectId: args.sourceRecordId,
        inDrawer: args.inDrawer,
        recordId: args.recordId,
        recordModel: args.recordModel,
        actionType: args.actionType,
        inputValues: args.inputValues,
        parentRecordModel: args.parentRecordModel,
        customActionCode: args.customActionCode,
      },
    });

    drawerRef.afterClose.subscribe(() => {
      try {
        args.parentComponent.recordPageDrawerClosed();
      } catch (e) {
        console.log(e);
      }
    });
    drawerRef.afterOpen.subscribe(() => {
      const recordPageComponent = drawerRef.getContentComponent();
      recordPageComponent.backButtonClicked.subscribe(() => {
        drawerRef.close();
      });
      recordPageComponent.objectSubmitted.subscribe(($event) => {
        args.parentComponent.linkedObjectSubmitted($event, args);
        if (args.actionType.toLowerCase() === 'add') {
          drawerRef.close();
        }
      });
    });
  }

我的问题是:销毁 RecordPage 组件后,静态函数中的订阅者仍然存在并导致问题。

同时使您的 drawerRef 静态,然后您必须实施 ondestroy 生命周期挂钩。

例子=

private ngOnDestroy () {
    drawerRef= null;
}

这里有两个问题:

  1. 您的订阅存在于父组件中(不存在于RecordPageComponent中),因此销毁记录页面组件不会影响这些订阅。

  2. 您需要手动退订所有订阅。按照以下步骤取消订阅这些

// create this to store all subscriptions
    subscription1$: Subscription 
    subscriptions: Subscription[] = [];

// store subscriptions in array like this
    this.subscription1$ = fcall.subscribe(x => //body);
    this.subscriptions.push(this.subscription1$)

// call this function to unsubscribe when you  want to do it
    unsubscribeAll() {
        this.subscriptions.forEach((subscription) => 
        subscription.unsubscribe())
    }