2

I have this code which opens a modal. When the modal is closed a call to this.loadClientOccupations() happens and information is refreshed.

  openAddOccupationComponent(servicePeriod: IServicePeriod): void {
    this.diaglogRef.open(OccupationAddComponent, {
      width: '25%',
      minHeight: '60%',
      data: {
        servicePeriod: servicePeriod
      },
      panelClass: 'no-padding-modal',
      disableClose: true
    });

    this.diaglogRef.afterAllClosed.subscribe(() => {
      this.loadClientOccupations();
    })
  }

What happens though is if you open the modal again and then close it, two calls to this.loadClientOccupations() happens. Open the modal a third time and close it and then three calls to this.loadClientOccupations() happens. This just keeps growing. Is there a way for me to limit these calls to just the first event? Is something not being destroyed that needs to be? This is the code that closes the modal.

  addOccupation(occupationDetails: IOccupation){
const occupation: IAddClientOccupationDetails = {
  occupationId: occupationDetails.id,
  servicePeriodSequence: this.data.servicePeriod.servicePeriodSequence,
  endDate: this.addOccupationForm.controls['endDate'].value,
  reserveClassType: this.addOccupationForm.controls['reserveClass'].value,
  startDate: this.addOccupationForm.controls['startDate'].value,
  clientId: this.clientId
};

let command: IAddClientOccupationsCommand = {
  clientOccupationInformation : occupation
};

this.clientOccupationService.addClientOccupations(command).subscribe(res =>
{
  this.dialogRef.close(occupation);
},(err: HttpErrorResponse) => {
  this.occupationEditError = new CarsError();
  this.occupationEditError.errorMessages = err.error.errors.ClientOccupationInformation;
  console.log(this.occupationEditError);
});

}

FAISAL
  • 33,618
  • 10
  • 97
  • 105

1 Answers1

3

Use the afterClosed() method instead of afterAllClosed. Also, to avoid any memory leaks, you need to unsubscribe from the subscription. In your case use the take operator. So your code would become:

openAddOccupationComponent(servicePeriod: IServicePeriod): void {
  const diaglogRef = this.diaglog.open(OccupationAddComponent, {
  width: '25%',
  minHeight: '60%',
  data: {
    servicePeriod: servicePeriod
  },
  panelClass: 'no-padding-modal',
  disableClose: true
});

dialogRef.afterClosed().pipe(
    take(1)
).subscribe(() => {
    this.loadClientOccupations();
})

}

Change your constructor to:

constructor(dialog: MatDialog) { }

Link to official documentation examples. Please check the code here for more information.

FAISAL
  • 33,618
  • 10
  • 97
  • 105