From e2753696ca22fefdd1b0dee00bde3386c6a92ecc Mon Sep 17 00:00:00 2001 From: Paul Irwin Date: Wed, 26 Jul 2023 09:59:36 -0600 Subject: [PATCH] Fix: #198 - Error thrown in ngOnDestroy if plot not yet initialized This can occur in unit tests if you do not await the component being stable, so this resolves #198. However, this could also happen if ngOnDestroy is called very quickly after ngOnInit. --- projects/plotly/src/lib/plotly.component.spec.ts | 5 +++++ projects/plotly/src/lib/plotly.component.ts | 8 +++++--- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/projects/plotly/src/lib/plotly.component.spec.ts b/projects/plotly/src/lib/plotly.component.spec.ts index 1958db1..7de2983 100644 --- a/projects/plotly/src/lib/plotly.component.spec.ts +++ b/projects/plotly/src/lib/plotly.component.spec.ts @@ -242,4 +242,9 @@ describe('PlotlyComponent', () => { expect(component.loadTheme).not.toHaveBeenCalled(); expect(component.themeLoader.load).not.toHaveBeenCalledOnceWith('plotly_dark'); }); + + it('should not cause errors if ngOnDestroy is called before plotly is initialized', () => { + // note that this test intentionally does not call ngOnInit/whenStable + expect(() => component.ngOnDestroy()).not.toThrow(); + }); }); diff --git a/projects/plotly/src/lib/plotly.component.ts b/projects/plotly/src/lib/plotly.component.ts index 6f9f0f3..ec2f0c6 100644 --- a/projects/plotly/src/lib/plotly.component.ts +++ b/projects/plotly/src/lib/plotly.component.ts @@ -143,9 +143,11 @@ export class PlotlyComponent implements OnInit, OnChanges, OnDestroy, DoCheck { this.resizeHandler = undefined; } - const figure = this.createFigure(); - this.purge.emit(figure); - PlotlyService.remove(this.plotlyInstance!); + if (this.plotlyInstance) { + const figure = this.createFigure(); + this.purge.emit(figure); + PlotlyService.remove(this.plotlyInstance); + } } ngOnChanges(changes: SimpleChanges): void {