Search code examples
angulardestroysubscribeng-zorro-antd

Angular - Destroy component manually using function


I have a component (RecordPage) being created from another component using a static function :

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

my problem is : after destroying the RecordPage component the subscribers in the static function still alive and cause issues.


Solution

  • There are two issues here:

    1. You subscription are present in parent component (not in RecordPageComponent), So the destroying the record page component won't affect these subscriptions.

    2. You need to unsubscribe all the subscriptions manually. Follow the below to unsubscribe these

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