diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d3cbe8fa..9a3574bc7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ $ npm install @ngxs/store@dev ### To become next patch version -- ... +- Fix(websocket-plugin): Do not dispatch action when root injector is destroyed [#2257](https://github.com/ngxs/store/pull/2257) ### 18.1.5 2024-11-12 diff --git a/packages/websocket-plugin/src/websocket-handler.ts b/packages/websocket-plugin/src/websocket-handler.ts index 05698cbc9..562f3375a 100644 --- a/packages/websocket-plugin/src/websocket-handler.ts +++ b/packages/websocket-plugin/src/websocket-handler.ts @@ -1,8 +1,7 @@ -import { Injectable, Inject, OnDestroy, NgZone } from '@angular/core'; +import { Injectable, Inject, NgZone, inject, DestroyRef } from '@angular/core'; import { Actions, Store, ofActionDispatched } from '@ngxs/store'; import { getValue } from '@ngxs/store/plugins'; -import { ReplaySubject, Subject, fromEvent } from 'rxjs'; -import { takeUntil } from 'rxjs/operators'; +import { ReplaySubject, Subject, fromEvent, takeUntil } from 'rxjs'; import { ConnectWebSocket, @@ -18,7 +17,7 @@ import { } from './symbols'; @Injectable({ providedIn: 'root' }) -export class WebSocketHandler implements OnDestroy { +export class WebSocketHandler { private _socket: WebSocket | null = null; private readonly _socketClosed$ = new Subject(); @@ -34,11 +33,12 @@ export class WebSocketHandler implements OnDestroy { @Inject(NGXS_WEBSOCKET_OPTIONS) private _options: NgxsWebSocketPluginOptions ) { this._setupActionsListeners(); - } - ngOnDestroy(): void { - this._disconnect(/* forcelyCloseSocket */ true); - this._destroy$.next(); + const destroyRef = inject(DestroyRef); + destroyRef.onDestroy(() => { + this._closeConnection(/* forcelyCloseSocket */ true); + this._destroy$.next(); + }); } private _setupActionsListeners(): void { diff --git a/packages/websocket-plugin/tests/websocket-handler-cleanup.spec.ts b/packages/websocket-plugin/tests/websocket-handler-cleanup.spec.ts index f3ab9b6bd..eddd2acc9 100644 --- a/packages/websocket-plugin/tests/websocket-handler-cleanup.spec.ts +++ b/packages/websocket-plugin/tests/websocket-handler-cleanup.spec.ts @@ -43,7 +43,8 @@ describe('WebSocketHandler cleanup', () => { ); const store = ngModuleRef.injector.get(Store); const webSocketHandler = ngModuleRef.injector.get(WebSocketHandler); - const ngOnDestroySpy = jest.spyOn(webSocketHandler, 'ngOnDestroy'); + const nextSpy = jest.fn(); + webSocketHandler['_destroy$'].subscribe(nextSpy); store.dispatch(new ConnectWebSocket()); @@ -51,7 +52,7 @@ describe('WebSocketHandler cleanup', () => { server.on('close', () => { try { // Assert - expect(ngOnDestroySpy).toHaveBeenCalled(); + expect(nextSpy).toHaveBeenCalled(); } finally { server.stop(done); }