import { provideEffects } from '@ngrx/effects';
import { loginReducers } from './store/login.reducers';
import { LoginEffects } from './store/login.effects';
+import { loginMetaReducer } from './store/login.metareducer';
export const appConfig: ApplicationConfig = {
providers: [
- provideStore({ login : loginReducers }),
+ provideStore({ login : loginReducers }, { metaReducers: [loginMetaReducer] }),
provideEffects([LoginEffects]),
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes)
--- /dev/null
+import { Action, ActionReducer, INIT, UPDATE } from '@ngrx/store';
+import { State } from './login.reducers';
+
+const STORAGE_KEY = 'login';
+
+function saveStateSlice(state: State) {
+ const { username } = state;
+ return { username };
+}
+
+export function loginMetaReducer<S, A extends Action<string>>(reducer: ActionReducer<S, A>): ActionReducer<S, A> {
+ return (state, action) => {
+ // 1) Rehydrate beim App-Start
+ if (action.type === INIT || action.type === UPDATE) {
+ const storedState = localStorage.getItem(STORAGE_KEY);
+ if (storedState) {
+ try {
+ const parsed = JSON.parse(storedState) as Partial<State>;
+ // vorhandenen State um gespeicherte Felder erweitern
+ return {
+ ...state,
+ login: {
+ ...(state as any)?.login,
+ ...parsed
+ }
+ };
+ } catch {
+ localStorage.removeItem(STORAGE_KEY);
+ }
+ }
+ }
+
+ // 2) Normal Reducer ausführen
+ const nextState : any = reducer(state, action);
+
+ // 3) Nur login-Slice persistieren
+ const loginSlice = (nextState as any)?.login as State;
+ if (loginSlice) {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(saveStateSlice(loginSlice)));
+ }
+
+ return nextState;
+ };
+}