Migrate global app state to signals library

This commit is contained in:
Z. Charles Dziura 2025-07-01 10:03:08 -04:00
parent 8e026944aa
commit f2d67bc56f
6 changed files with 20 additions and 37 deletions

View file

@ -1,23 +1,15 @@
import {
ApplicationConfig,
importProvidersFrom,
isDevMode,
provideBrowserGlobalErrorListeners,
provideZonelessChangeDetection,
} from '@angular/core';
import { StoreModule } from '@ngrx/store';
import { provideStoreDevtools } from '@ngrx/store-devtools';
import { appStateReducer } from './state/state.reducer';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideZonelessChangeDetection(),
importProvidersFrom(
StoreModule.forRoot({
app: appStateReducer,
})
),
provideStoreDevtools({
maxAge: 25,
logOnly: !isDevMode(),

View file

@ -1,5 +1,5 @@
<main>
@switch (currentView$ | async) {
@switch (currentView()) {
@default {
<app-starting-point></app-starting-point>
}

15
src/app/app.state.ts Normal file
View file

@ -0,0 +1,15 @@
import { signalStore, withState } from '@ngrx/signals';
export type AppState = {
currentView: CurrentView;
};
export enum CurrentView {
StartingPoint = 'startingPoint',
}
const initialState: AppState = {
currentView: CurrentView.StartingPoint,
};
export const AppStateStore = signalStore({ providedIn: 'root' }, withState(initialState));

View file

@ -1,7 +1,5 @@
import { AsyncPipe } from '@angular/common';
import { ChangeDetectionStrategy, Component, inject, OnInit } from '@angular/core';
import { select, Store } from '@ngrx/store';
import { selectCurrentView } from './state/state.selectors';
import { AppStateStore } from './app.state';
import { StartingPoint } from './views/starting-point/starting-point';
@Component({
@ -9,12 +7,11 @@ import { StartingPoint } from './views/starting-point/starting-point';
templateUrl: './app.html',
styleUrl: './app.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [AsyncPipe, StartingPoint],
imports: [StartingPoint],
})
export class App implements OnInit {
private readonly store$ = inject(Store);
readonly currentView$ = this.store$.pipe(select(selectCurrentView));
private readonly state = inject(AppStateStore);
readonly currentView = this.state.currentView;
ngOnInit(): void {}
}

View file

@ -1,15 +0,0 @@
import { createReducer } from '@ngrx/store';
export interface AppState {
currentView: CurrentView;
}
export enum CurrentView {
StartingPoint = 'startingPoint',
}
export const initialState: AppState = {
currentView: CurrentView.StartingPoint,
};
export const appStateReducer = createReducer(initialState);

View file

@ -1,6 +0,0 @@
import { createFeatureSelector, createSelector } from '@ngrx/store';
import { AppState } from './state.reducer';
export const selectAppState = createFeatureSelector<AppState>('app');
export const selectCurrentView = createSelector(selectAppState, (state: AppState) => state.currentView);