Skip to content

Commit

Permalink
fix(signals): run onDestroy outside of injection context (#4200)
Browse files Browse the repository at this point in the history
  • Loading branch information
rainerhahnekamp authored Jan 7, 2024
1 parent 1b5458d commit e21df19
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 19 deletions.
20 changes: 19 additions & 1 deletion modules/signals/spec/signal-store.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,8 @@ describe('signalStore', () => {
expect(message).toBe('onDestroy');
});

// FIX: injection context will be provided for `onDestroy` in a separate PR
// see https://github.com/ngrx/platform/pull/4196#issuecomment-1875228588
it('executes hooks in injection context', () => {
const messages: string[] = [];
const TOKEN = new InjectionToken('TOKEN', {
Expand All @@ -281,7 +283,7 @@ describe('signalStore', () => {
messages.push('onInit');
},
onDestroy() {
inject(TOKEN);
// inject(TOKEN);
messages.push('onDestroy');
},
})
Expand All @@ -293,6 +295,22 @@ describe('signalStore', () => {
destroy();
expect(messages).toEqual(['onInit', 'onDestroy']);
});

it('succeeds with onDestroy and providedIn: root', () => {
const messages: string[] = [];
const Store = signalStore(
{ providedIn: 'root' },
withHooks({
onDestroy() {
messages.push('ending...');
},
})
);
TestBed.inject(Store);
TestBed.resetTestEnvironment();

expect(messages).toEqual(['ending...']);
});
});

describe('composition', () => {
Expand Down
26 changes: 8 additions & 18 deletions modules/signals/src/signal-store.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,13 @@
import {
DestroyRef,
inject,
Injectable,
Injector,
runInInjectionContext,
signal,
Type,
} from '@angular/core';
import { DestroyRef, inject, Injectable, signal, Type } from '@angular/core';
import { STATE_SIGNAL, StateSignal } from './state-signal';
import {
EmptyFeatureResult,
InnerSignalStore,
MergeFeatureResults,
SignalStoreProps,
SignalStoreConfig,
SignalStoreFeature,
SignalStoreFeatureResult,
SignalStoreProps,
} from './signal-store-models';
import { Prettify } from './ts-helpers';

Expand Down Expand Up @@ -325,16 +317,14 @@ export function signalStore(
(this as any)[key] = props[key];
}

if (hooks.onInit) {
hooks.onInit();
}
const { onInit, onDestroy } = hooks;

if (hooks.onDestroy) {
const injector = inject(Injector);
if (onInit) {
onInit();
}

inject(DestroyRef).onDestroy(() => {
runInInjectionContext(injector, hooks.onDestroy!);
});
if (onDestroy) {
inject(DestroyRef).onDestroy(onDestroy);
}
}
}
Expand Down

0 comments on commit e21df19

Please sign in to comment.