【问题标题】:Angular - Destroy component manually using functionAngular - 使用函数手动销毁组件
【发布时间】:2022-01-05 09:04:34
【问题描述】:

我有一个使用静态函数从另一个组件创建的组件(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 组件后,静态函数中的订阅者仍然存在并导致问题。

【问题讨论】:

    标签: angular destroy subscribe ng-zorro-antd


    【解决方案1】:

    这里有两个问题:

    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())
        }
    

    【讨论】:

      【解决方案2】:

      drawerRef 设为静态,然后您必须实现ondestroy 生命周期挂钩。

      示例=

      private ngOnDestroy () {
          drawerRef= null;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-26
        • 1970-01-01
        • 2018-12-17
        • 2016-12-05
        • 2019-07-28
        • 1970-01-01
        • 2019-02-18
        • 2022-01-03
        相关资源
        最近更新 更多