### Serve NGXS Integration Examples Source: https://github.com/ngxs/store/blob/master/docs/community-and-labs/community/developer-guide.md Launches a local development server to run and view the integration examples provided with NGXS. This helps in testing changes in a live environment. ```bash yarn start ``` -------------------------------- ### Install NGXS Tutorial Dependencies Source: https://github.com/ngxs/store/blob/master/docs/community-and-labs/community/developer-guide.md Installs dependencies specifically for the 'create-app' tutorial within the NGXS project. This command uses the `--cwd` flag to specify the working directory. ```bash yarn --cwd tutorials/create-app ``` -------------------------------- ### Install Node.js Dependencies for NGXS Project Source: https://github.com/ngxs/store/blob/master/tutorials/create-app/src/content/tutorial/meta.md Installs all required Node.js packages and project dependencies using npm. This command should be run once after cloning the repository or when dependencies are updated. ```Shell npm install ``` -------------------------------- ### Install NGXS Root Dependencies Source: https://github.com/ngxs/store/blob/master/docs/community-and-labs/community/developer-guide.md Installs the primary project dependencies for the NGXS repository using Yarn. This command should be run from the root directory after cloning. ```bash yarn install ``` -------------------------------- ### Start Angular Application with NGXS Store Source: https://github.com/ngxs/store/blob/master/tutorials/create-app/src/content/tutorial/meta.md Launches the Angular development server, making the application accessible in a web browser. This command typically starts the application in watch mode, recompiling on code changes. ```Shell npm run start ``` -------------------------------- ### Build All NGXS Packages Source: https://github.com/ngxs/store/blob/master/docs/community-and-labs/community/developer-guide.md Compiles and builds all packages defined within the NGXS monorepo. This command is essential after installing dependencies or before running tests/examples. ```bash yarn build:packages ``` -------------------------------- ### NGXS Development Build Dependency in package.json Source: https://github.com/ngxs/store/blob/master/docs/introduction/installation.md An example of how a development build version of `@ngxs/store` appears in the `dependencies` section of a `package.json` file after installation. ```json { "dependencies": { "@ngxs/store": "3.0.0-dev.a0d076d" } } ``` -------------------------------- ### Install NGXS Starter Kit specifying custom path Source: https://github.com/ngxs/store/blob/master/docs/introduction/starter-kit.md This command allows installing the NGXS Starter Kit via Angular schematics, explicitly setting the installation path using the `--path` option. This bypasses the interactive prompt for the path. ```bash ng generate @ngxs/store:starter-kit --path YOUR_PATH ``` -------------------------------- ### Install NGXS Starter Kit using default schematics Source: https://github.com/ngxs/store/blob/master/docs/introduction/starter-kit.md This command uses Angular schematics to generate the NGXS Starter Kit. Running it will prompt the user to configure the installation, including path and other options. ```bash ng generate @ngxs/store:starter-kit ``` -------------------------------- ### Install NGXS Development Builds Source: https://github.com/ngxs/store/blob/master/docs/introduction/installation.md Commands to install the latest development builds of `@ngxs/store` and its plugins using the `@dev` tag. This allows access to bleeding-edge features and fixes, but requires re-running the command to update to newer dev builds. ```bash npm install @ngxs/store@dev npm install @ngxs/logger-plugin@dev npm install @ngxs/devtools-plugin@dev ``` ```bash yarn add @ngxs/store@dev yarn add @ngxs/logger-plugin@dev yarn add @ngxs/devtools-plugin@dev ``` ```bash yarn add @ngxs/{store,logger-plugin,devtools-plugin}@dev ``` ```bash pnpm install @ngxs/store@dev pnpm install @ngxs/logger-plugin@dev pnpm install @ngxs/devtools-plugin@dev ``` -------------------------------- ### Install NGXS CLI Source: https://github.com/ngxs/store/blob/master/docs/plugins/cli.md Instructions to install the NGXS Command Line Interface globally using either npm or yarn package managers, allowing it to be run from any directory. ```bash npm install @ngxs/cli -g ``` ```bash yarn global add @ngxs/cli ``` -------------------------------- ### Install NGXS Storage Plugin Source: https://github.com/ngxs/store/blob/master/docs/plugins/storage.md Instructions to install the @ngxs/storage-plugin using npm, yarn, or pnpm. ```bash npm i @ngxs/storage-plugin # or if you are using yarn yarn add @ngxs/storage-plugin # or if you are using pnpm pnpm i @ngxs/storage-plugin ``` -------------------------------- ### Run NGXS Store Development Watch Source: https://github.com/ngxs/store/blob/master/docs/community-and-labs/community/developer-guide.md Starts development mode for the `@ngxs/store` package, continuously watching for file changes and automatically rebuilding. This is used for active development on the core store. ```bash yarn build:packages --package store --watch ``` -------------------------------- ### Manually Install NGXS Store Package Source: https://github.com/ngxs/store/blob/master/docs/introduction/installation.md Instructions for manually installing the `@ngxs/store` package using npm, yarn, or pnpm. This method requires subsequent manual configuration of the store in your Angular application. ```bash npm i @ngxs/store ``` ```bash yarn add @ngxs/store ``` ```bash pnpm i @ngxs/store ``` -------------------------------- ### Install NGXS Project Dependencies Source: https://github.com/ngxs/store/blob/master/CONTRIBUTING.md This command installs all necessary project dependencies for the NGXS repository, preparing the environment for development. ```bash yarn ``` -------------------------------- ### Unit Testing NGXS States: Basic Setup and Action Dispatch Source: https://github.com/ngxs/store/blob/master/docs/recipes/unit-testing.md This snippet demonstrates the fundamental setup for unit testing NGXS states. It shows how to configure `TestBed` with `provideStore`, inject the `Store`, dispatch an action, and assert state changes using `selectSnapshot` for synchronous state retrieval. ```ts import { TestBed } from '@angular/core/testing'; import { provideStore, Store } from '@ngxs/store'; import { ZooState } from './zoo.state'; import { FeedAnimals } from './zoo.actions'; describe('Zoo', () => { let store: Store; beforeEach(() => { TestBed.configureTestingModule({ providers: [provideStore([ZooState])] }); store = TestBed.inject(Store); }); it('it toggles feed', () => { store.dispatch(new FeedAnimals()); const feed = store.selectSnapshot(ZooState.getFeed); expect(feed).toBe(true); }); }); ``` -------------------------------- ### Configure NGXS Store in Angular Application Source: https://github.com/ngxs/store/blob/master/docs/introduction/installation.md Example demonstrating how to configure the NGXS store in an Angular application. For standalone projects, `provideStore` is added to `app.config.ts` providers. For module-based applications, `NgxsModule.forRoot([])` is added to `app.module.ts` imports. ```typescript import { provideStore } from '@ngxs/store'; export const appConfig: ApplicationConfig = { providers: [provideStore()] }; ``` -------------------------------- ### Install Ngxs WebSocket Plugin Source: https://github.com/ngxs/store/blob/master/docs/plugins/websocket.md Instructions for installing the Ngxs WebSocket plugin using npm, yarn, or pnpm package managers. ```bash npm i @ngxs/websocket-plugin # or if you are using yarn yarn add @ngxs/websocket-plugin # or if you are using pnpm pnpm i @ngxs/websocket-plugin ``` -------------------------------- ### Basic NGXS CLI Usage Source: https://github.com/ngxs/store/blob/master/docs/plugins/cli.md Demonstrates the fundamental command to execute the NGXS CLI after it has been successfully installed globally. ```bash ngxs ``` -------------------------------- ### Install NGXS Store with Angular Schematics Source: https://github.com/ngxs/store/blob/master/docs/introduction/installation.md Use Angular schematics to automatically install `@ngxs/store` and optionally select plugins and target projects. This command updates `package.json` and installs dependencies, configuring the store for standalone or module-based applications. ```bash ng add @ngxs/store ``` ```bash ng add @ngxs/store --plugins DEVTOOLS,FORM --project angular-ngxs-project ``` -------------------------------- ### Install NGXS Router Plugin Source: https://github.com/ngxs/store/blob/master/docs/plugins/router.md Instructions on how to install the `@ngxs/router-plugin` package using common package managers like npm, yarn, or pnpm. ```bash npm i @ngxs/router-plugin # or if you are using yarn yarn add @ngxs/router-plugin # or if you are using pnpm pnpm i @ngxs/router-plugin ``` -------------------------------- ### Install NGXS Form Plugin Source: https://github.com/ngxs/store/blob/master/docs/plugins/form.md Instructions on how to install the NGXS Form Plugin using npm, yarn, or pnpm package managers. ```bash npm i @ngxs/form-plugin # or if you are using yarn yarn add @ngxs/form-plugin # or if you are using pnpm pnpm i @ngxs/form-plugin ``` -------------------------------- ### Install and Configure NGXS Store Source: https://github.com/ngxs/store/blob/master/publication/2024-06-10_announcing_ngxs_18/article.md Automate the installation and initial configuration of the NGXS store in an Angular application. This command prompts for project selection in multi-project workspaces and allows for interactive plugin selection. ```bash ng add @ngxs/store ``` -------------------------------- ### Start NGXS Integration Application Source: https://github.com/ngxs/store/blob/master/CONTRIBUTING.md Launches the integration application, allowing developers to interactively test and play around with the NGXS library. ```bash yarn start ``` -------------------------------- ### Install NGXS Store with ng-add Schematic Source: https://github.com/ngxs/store/blob/master/tutorials/create-app/src/content/tutorial/1-create-a-todo-app/2-installation/1-using-schematics/content.md Use the Angular CLI's ng-add command to automatically install the @ngxs/store package and update the project's package.json file. This command ensures the correct version of NGXS is installed based on the Angular version (NGXS v.18 requires Angular >= v.17). ```bash ng add @ngxs/store ``` -------------------------------- ### Configure Angular APP_INITIALIZER for Application Startup Source: https://github.com/ngxs/store/blob/master/docs/concepts/state/life-cycle.md Illustrates how to use the `APP_INITIALIZER` token in Angular to run initialization logic before the application fully starts. This token references Promise factories, allowing for asynchronous setup tasks. It's useful for pre-loading data or configuring services. ```ts export function appInitializerFactory() { return () => Promise.resolve(); } export const appConfig: ApplicationConfig = { providers: [ { provide: APP_INITIALIZER, useFactory: appInitializerFactory, multi: true } ] }; ``` -------------------------------- ### NGXS Starter Kit Schematic Command Options Source: https://github.com/ngxs/store/blob/master/docs/introduction/starter-kit.md This API documentation outlines the configurable options for the NGXS Starter Kit schematic. It details each option's purpose, whether it's mandatory, and its default value, guiding users on how to customize the generation process. ```APIDOC Schematic Options: --path: Description: The path to create the starter kit Required: Yes Default Value: (None) --spec: Description: Boolean flag to indicate if a unit test file should be created Required: No Default Value: true --project: Description: Name of the project as it is defined in your angular.json Required: No Default Value: Workspace's default project ``` -------------------------------- ### NGXS Git Commit Message Examples Source: https://github.com/ngxs/store/blob/master/CONTRIBUTING.md Provides examples of valid Git commit messages adhering to the NGXS project's guidelines, demonstrating the header, body, and footer components for different commit types like documentation updates and bug fixes. ```text docs(changelog): update changelog to beta.5 ``` ```text fix(release): need to depend on latest rxjs The version in our package.json gets copied to the one we publish, and users need the latest of these. ``` -------------------------------- ### Managing State Content: Avoid Class Instances, Prefer Plain Objects Source: https://github.com/ngxs/store/blob/master/docs/style-guide.md Demonstrates the recommended approach for storing data in NGXS state. It contrasts storing class-based instances, which are difficult to serialize and mutate, with storing plain object literals, which are immutable, easily serializable, and align with state management principles. Includes examples of state definition, selectors, actions, and component usage. ```typescript export class Todo { constructor( readonly title: string, readonly isCompleted = false ) {} } @State ({ name: 'todos', defaults: [] }) @Injectable() class TodosState { @Selector() static getTodos(state: Todo[]) { return state; } @Action(AddTodo) add(ctx: StateContext, action: AddTodo): void { // Avoid new Todo(title) ctx.setState((state: Todo[]) => state.concat(new Todo(action.title))); } } @Component({ selector: 'app', template: ` @for (todo of todos(); track todo) { {{ todo.isCompleted }} } ` }) class AppComponent { todos = inject(Store).selectSignal(TodosState.getTodos); } ``` ```typescript export interface TodoModel { title: string; isCompleted: boolean; } @State ({ name: 'todos', defaults: [] }) @Injectable() class TodosState { @Selector() static getTodos(state: Todo[]) { return state; } @Action(AddTodo) add(ctx: StateContext, action: AddTodo): void { ctx.setState((state: TodoModel[]) => state.concat({ title: action.title, isCompleted: false }) ); } } @Component({ selector: 'app', template: ` @for (todo of todos(); track todo) { {{ todo.isCompleted }} } ` }) class AppComponent { todos = inject(Store).selectSignal(TodosState.getTodos); } ``` -------------------------------- ### Configure NGXS Storage Plugin with NgxsModule (Modules) Source: https://github.com/ngxs/store/blob/master/docs/plugins/storage.md Example demonstrating how to integrate the NGXS Storage Plugin into an Angular application using `NgxsModule.forRoot` and `NgxsStoragePluginModule.forRoot` in a traditional NgModule setup. ```ts import { NgxsModule } from '@ngxs/store'; import { NgxsStoragePluginModule } from '@ngxs/storage-plugin'; @NgModule({ imports: [NgxsModule.forRoot([]), NgxsStoragePluginModule.forRoot({ keys: '*' })] }) export class AppModule {} ``` -------------------------------- ### Run New NGXS Package Development Watch Source: https://github.com/ngxs/store/blob/master/docs/community-and-labs/community/developer-guide.md Initiates development mode for a newly created NGXS package, watching for changes and rebuilding. Replace `` with the actual name of your new package. ```bash yarn build:packages --package --watch ``` -------------------------------- ### Install NGXS Logger Plugin Source: https://github.com/ngxs/store/blob/master/docs/plugins/logger.md Instructions for installing the `@ngxs/logger-plugin` package using common package managers like npm, yarn, and pnpm. This step is required before using the plugin in your Angular application. ```bash npm i @ngxs/logger-plugin # or if you are using yarn yarn add @ngxs/logger-plugin # or if you are using pnpm pnpm i @ngxs/logger-plugin ``` -------------------------------- ### Start HMR development environment Source: https://github.com/ngxs/store/blob/master/docs/plugins/hmr.md Command to start the Angular application with HMR enabled using the previously configured `npm run hmr` shortcut. ```bash npm run hmr ``` -------------------------------- ### Build a Specific NGXS Package Source: https://github.com/ngxs/store/blob/master/docs/community-and-labs/community/developer-guide.md Compiles and builds a single specified package within the NGXS monorepo. Replace `` with the actual name of the package to build. ```bash yarn build:packages --package ``` -------------------------------- ### Unit Testing NGXS Selectors: Static and Dynamic Examples Source: https://github.com/ngxs/store/blob/master/docs/recipes/unit-testing.md This section provides examples for unit testing NGXS selectors. It covers testing simple, static selectors by directly calling `selectSnapshot` and also demonstrates how to test dynamic selectors created with `createSelector` by mocking the state and passing it as an argument to the selector function. ```ts import { TestBed } from '@angular/core/testing'; import { Store } from '@ngxs/store'; import { ZooState } from './zoo.state'; describe('Zoo', () => { let store: Store; beforeEach(() => { TestBed.configureTestingModule({ providers: [Store] }); store = TestBed.inject(Store); }); it('it should select pandas', () => { const pandas = store.selectSnapshot(ZooState.getPandas); expect(pandas).toEqual(['pandas']); }); }); ``` ```ts export class ZooSelectors { static getAnimalNames = (type: string) => { return createSelector([ZooState], (state: ZooStateModel) => state.animals.filter(animal => animal.type === type).map(animal => animal.name) ); }; } it('should select requested animal names from state', () => { const zooState = { animals: [ { type: 'zebra', name: 'Andy' }, { type: 'panda', name: 'Betty' }, { type: 'zebra', name: 'Crystal' }, { type: 'panda', name: 'Donny' } ] }; const value = ZooSelectors.getAnimalNames('zebra')(zooState); expect(value).toEqual(['Andy', 'Crystal']); }); ``` -------------------------------- ### Activate NgxsSentryBreadcrumbsService with APP_INITIALIZER Source: https://github.com/ngxs/store/blob/master/docs/recipes/integration-with-sentry.md This snippet demonstrates how to ensure the `NgxsSentryBreadcrumbsService` is instantiated and starts monitoring NGXS actions as soon as the application initializes. By providing it as a dependency of `APP_INITIALIZER`, the service's constructor is called early, enabling continuous tracing of actions to Sentry from the application's start. ```ts provideAppInitializer(() => inject(NgxsSentryBreadcrumbsService)); ``` -------------------------------- ### Displaying Simple Values from Observables in Angular Template Source: https://github.com/ngxs/store/blob/master/integration/app/list/list.component.html Examples demonstrating how to display basic values from Angular Observables using the `async` pipe within HTML templates. This is a common pattern for reactive data streams, ensuring automatic unsubscription when the component is destroyed. ```Angular Template {{ list$ | async }} ``` ```Angular Template {{ hello$ | async }} ``` -------------------------------- ### Todo Form UI Elements and Data Binding Source: https://github.com/ngxs/store/blob/master/integration/app/app.component.html Presents UI elements and data binding for a todo list, showcasing observable and signal-based data access, an 'Add' action, and navigation links. ```HTML Add * (todos$) {{ todo }} 🗑 * (todos() signal) {{ todo }} 🗑 * (pandas$) 🐼 * (pandas() signal) 🐼 List Detail Counter ``` -------------------------------- ### Reactive Form UI Elements and Data Binding Source: https://github.com/ngxs/store/blob/master/integration/app/app.component.html Illustrates UI elements and data binding patterns for a reactive form, including asynchronous data display using `async` pipe, signal access, and array iteration. Also lists associated actions. ```HTML (injected$) {{ injected$ | async }} (injected() signal) {{ injected() }} Toppings: Crust Extras {{ allExtras[i].name }} Set Olives Set Prefix Load Data ``` -------------------------------- ### Run NGXS Project Tests Source: https://github.com/ngxs/store/blob/master/docs/community-and-labs/community/developer-guide.md Executes all unit and integration tests across the NGXS project. Running tests is crucial to ensure code quality and prevent regressions before committing changes. ```bash yarn test ``` -------------------------------- ### Node.js WebSocket Server Example Source: https://github.com/ngxs/store/blob/master/docs/plugins/websocket.md Provides a basic Node.js server implementation using `ws` and `express` that listens for WebSocket connections, processes incoming messages, and broadcasts them to connected clients. ```js const { Server } = require('ws'); const { createServer } = require('http'); const app = require('express')(); const server = createServer(app); const ws = new Server({ server }); server.listen(4200); ws.on('connection', socket => { socket.on('message', data => { // That's the object that we passed into `SendWebSocketMessage` constructor const { type, from, message } = JSON.parse(data); if (type === 'message') { const event = JSON.stringify({ type: '[Chat] Add message', from, message }); // That's the same as `broadcast` // we want to send message to all connected // to the chat clients ws.clients.forEach(client => { client.send(event); }); } }); }); ``` -------------------------------- ### Displaying Simple Values from Signals in Angular Template Source: https://github.com/ngxs/store/blob/master/integration/app/list/list.component.html Examples illustrating how to display basic values from Angular Signals directly within HTML templates. Signals provide a new, simpler way for reactive state management in Angular, offering direct access to their current value. ```Angular Template {{ list() }} ``` ```Angular Template {{ hello() }} ``` -------------------------------- ### Install NGXS Redux Devtools Plugin Source: https://github.com/ngxs/store/blob/master/docs/plugins/devtools.md This snippet provides commands to install the `@ngxs/devtools-plugin` package using npm, yarn, or pnpm. This plugin enables integration with Redux Devtools for state inspection and debugging. ```bash npm i @ngxs/devtools-plugin # or if you are using yarn yarn add @ngxs/devtools-plugin # or if you are using pnpm pnpm i @ngxs/devtools-plugin ``` -------------------------------- ### Configure NGXS Storage Plugin with provideStore (Standalone API) Source: https://github.com/ngxs/store/blob/master/docs/plugins/storage.md Example demonstrating how to integrate the NGXS Storage Plugin into an Angular application using the `provideStore` function and `withNgxsStoragePlugin` in the `ApplicationConfig`. ```ts import { provideStore } from '@ngxs/store'; import { withNgxsStoragePlugin } from '@ngxs/storage-plugin'; export const appConfig: ApplicationConfig = { providers: [ provideStore( [], withNgxsStoragePlugin({ keys: '*' }) ) ] }; ``` -------------------------------- ### Create a New Git Branch for Pull Request Source: https://github.com/ngxs/store/blob/master/docs/community-and-labs/community/contributing.md Instructions on how to create a new local Git branch from the 'master' branch before starting work on a pull request, ensuring changes are isolated and do not directly affect the main branch. ```shell git checkout -b my-fix-branch master ``` -------------------------------- ### NGXS Dispatching Actions from Actions Source: https://github.com/ngxs/store/blob/master/docs/concepts/state/README.md Shows how to dispatch new actions from within an existing NGXS action using the `ctx.dispatch` method. It includes both a simple synchronous example and an asynchronous example that dispatches after an Observable chain completes, demonstrating how to chain actions. ```typescript import { Injectable } from '@angular/core'; import { State, Action, StateContext } from '@ngxs/store'; import { map } from 'rxjs'; export interface ZooStateModel { feedAnimals: string[]; } @State({ name: 'zoo', defaults: { feedAnimals: [] } }) @Injectable() export class ZooState { constructor(private animalService: AnimalService) {} /** * Simple Example */ @Action(FeedAnimals) feedAnimals(ctx: StateContext, action: FeedAnimals) { const state = ctx.getState(); ctx.setState({ ...state, feedAnimals: [...state.feedAnimals, action.animalsToFeed] }); return ctx.dispatch(new TakeAnimalsOutside()); } /** * Async Example */ @Action(FeedAnimals) feedAnimals2(ctx: StateContext, action: FeedAnimals) { return this.animalService.feed(action.animalsToFeed).pipe( tap(animalsToFeedResult => { const state = ctx.getState(); ctx.patchState({ feedAnimals: [...state.feedAnimals, animalsToFeedResult] }); }), mergeMap(() => ctx.dispatch(new TakeAnimalsOutside())) ); } } ``` -------------------------------- ### Register NGXS Plugin with provideStore Source: https://github.com/ngxs/store/blob/master/docs/plugins/README.md This snippet shows how to register a custom NGXS plugin, such as the logger plugin, with the `provideStore` function. It demonstrates how to include the plugin as an NGXS feature and optionally pass configuration options during application setup. ```ts export const appConfig: ApplicationConfig = { providers: [provideStore([ZooState], withNgxsLoggerPlugin({}))] }; ``` -------------------------------- ### Run Angular development server with HMR Source: https://github.com/ngxs/store/blob/master/docs/plugins/hmr.md Command to start the Angular development server with the HMR configuration enabled. ```bash ng serve --configuration hmr ``` -------------------------------- ### Implement NGXS Logger Plugin using a Pure Function Source: https://github.com/ngxs/store/blob/master/docs/plugins/README.md This example illustrates how to create an NGXS plugin using a pure function. It highlights that plugin functions operate within an injection context, allowing dependencies to be injected, and demonstrates logging actions before and after their execution. ```ts import { NgxsNextPluginFn } from '@ngxs/store/plugins'; export function logPlugin(state: any, action: any, next: NgxsNextPluginFn) { // Note that plugin functions are called within an injection context, // allowing you to inject dependencies. const options = inject(NGXS_LOGGER_PLUGIN_OPTIONS); console.log('Action started!', state); return next(state, action).pipe(tap(result) => { console.log('Action happened!', result); }); } ``` -------------------------------- ### Configure Ngxs WebSocket Plugin with provideStore (Standalone) Source: https://github.com/ngxs/store/blob/master/docs/plugins/websocket.md Example of configuring the Ngxs WebSocket plugin in an Angular application using `provideStore` for standalone components, specifying the WebSocket URL. ```typescript import { provideStore } from '@ngxs/store'; import { withNgxsWebSocketPlugin } from '@ngxs/websocket-plugin'; export const appConfig: ApplicationConfig = { providers: [ provideStore( [], withNgxsWebSocketPlugin({ url: 'ws://localhost:4200' }) ) ] }; ``` -------------------------------- ### Generate NGXS Store Interactively (Bash) Source: https://github.com/ngxs/store/blob/master/docs/concepts/store/schematics.md Use this command to generate an NGXS store through an interactive prompt. The schematic will guide you through configuring the store's name, path, and other options. ```bash ng generate @ngxs/store:store ``` -------------------------------- ### Create NGXS Action Listener for GetTodos Source: https://github.com/ngxs/store/blob/master/tutorials/create-app/src/content/tutorial/1-create-a-todo-app/3-get-todo-items/2-handle-the-action/content.md This TypeScript code defines an NGXS action listener for the `GetTodos` action. It uses the `@Action` decorator to associate the `get` method with `GetTodos`. Inside the method, it asynchronously fetches todo items from `_todoService.get()` and updates the `TodoStateModel` in the state context with the new data. ```ts @Action(GetTodos) async get(ctx: StateContext) { const todoItems = await firstValueFrom(this._todoService.get()); ctx.setState({ todos: todoItems, }); } ``` -------------------------------- ### Initialize Sentry in Angular Application Source: https://github.com/ngxs/store/blob/master/docs/recipes/integration-with-sentry.md This snippet demonstrates the initial setup of Sentry in an Angular application's `main.ts` file. It involves calling `Sentry.init(...)` to configure the Sentry DSN and other global settings, which is a prerequisite for using Sentry's error tracking capabilities. ```ts Sentry.init({ dsn: ... // ... }); ``` -------------------------------- ### NGXS State for Fetching All Novels Source: https://github.com/ngxs/store/blob/master/docs/recipes/cache.md This snippet defines a basic NGXS state and action (`NovelsState` and `GetNovels`) responsible for fetching a list of all novels from a service and setting them into the store. It serves as the foundation for subsequent caching examples. ```ts import { Injectable } from '@angular/core'; import { State, Action, StateContext } from '@ngxs/store'; import { tap } from 'rxjs'; export class GetNovels { static readonly type = '[Novels] Get novels'; } @State ({ name: 'novels', defaults: [] }) @Injectable() export class NovelsState { constructor(private novelsService: NovelsService) {} @Action(GetNovels) getNovels(ctx: StateContext) { return this.novelsService.getNovels().pipe(tap(novels => ctx.setState(novels))); } } ``` -------------------------------- ### Ensuring Node Modules are Up-to-Date with Yarn Source: https://github.com/ngxs/store/blob/master/yarn.lock.readme.md Run yarn install to synchronize your node_modules directory with the yarn.lock file, ensuring correct dependencies after a branch switch or repository update. ```Shell yarn install ``` -------------------------------- ### Navigate Programmatically using NGXS Store Source: https://github.com/ngxs/store/blob/master/docs/plugins/router.md Illustrates how to dispatch a `Navigate` action via the NGXS store's `dispatch` method to programmatically change routes, for example, navigating to the '/admin' page. ```ts import { Store } from '@ngxs/store'; import { Navigate } from '@ngxs/router-plugin'; @Component({ ... }) export class MyApp { constructor(private store: Store) {} onClick() { this.store.dispatch(new Navigate(['/admin'])) } } ``` -------------------------------- ### Implement a Custom NGXS Storage Engine Source: https://github.com/ngxs/store/blob/master/docs/plugins/storage.md This snippet provides an example of how to define a custom storage engine by implementing the `StorageEngine` interface. Custom engines are useful for scenarios like server-side rendering where default browser storage might not be available, or for integrating with alternative storage solutions. ```ts import { withNgxsStoragePlugin, StorageEngine } from '@ngxs/storage-plugin'; @Injectable({ providedIn: 'root' }) export class MyCustomStorageEngine implements StorageEngine { // ... } ``` -------------------------------- ### Generate NGXS State Interactively Source: https://github.com/ngxs/store/blob/master/docs/concepts/state/schematics.md Executes the NGXS state schematic, prompting the user to interactively provide configuration details for the new state. This is the simplest way to get started with state generation. ```bash ng generate @ngxs/store:state ``` -------------------------------- ### Provide Sentry ErrorHandler and TraceService in Angular Source: https://github.com/ngxs/store/blob/master/docs/recipes/integration-with-sentry.md This code illustrates how to make Sentry's `ErrorHandler` and `TraceService` available throughout your Angular application. It provides examples for both the modern `ApplicationConfig` approach and the traditional NgModule setup, ensuring Sentry can intercept errors and trace application flow. ```ts // app.config.ts export const appConfig: ApplicationConfig = { providers: [ // ... { provide: ErrorHandler, useValue: Sentry.createErrorHandler() }, provideAppInitializer(() => inject(Sentry.TraceService)) ] }; // Or using an old module approach: // app.module.ts @NgModule({ providers: [ // ... { provide: ErrorHandler, useValue: Sentry.createErrorHandler() }, provideAppInitializer(() => inject(Sentry.TraceService)) ] }) export class AppModule {} ``` -------------------------------- ### Generate NGXS Store with Custom Name (Bash) Source: https://github.com/ngxs/store/blob/master/docs/concepts/store/schematics.md This command allows direct generation of an NGXS store by specifying its name using the `--name` option. It bypasses the interactive prompt, enabling quick setup or scripting. ```bash ng generate @ngxs/store:store --name NAME_OF_YOUR_STORE ``` -------------------------------- ### Persist Feature States with NGXS Storage Plugin Source: https://github.com/ngxs/store/blob/master/docs/plugins/storage.md This example demonstrates how to persist specific states at the feature level using `provideStates` and `withStorageFeature`. It shows how to register `AnimalsState` within route providers and ensure it's persisted by the storage plugin. ```TypeScript import { provideStates } from '@ngxs/store'; import { withStorageFeature } from '@ngxs/storage-plugin'; export const routes: Routes = [ { path: 'animals', loadComponent: () => import('./animals'), providers: [provideStates([AnimalsState], withStorageFeature([AnimalsState]))] } ]; ``` -------------------------------- ### NGXS Action Schematics Command Options Source: https://github.com/ngxs/store/blob/master/docs/concepts/actions/schematics.md This section details the available command-line options for the `ng generate @ngxs/store:actions` schematic. It includes the option name, its description, whether it's required, and its default value, guiding users on how to customize action generation. ```APIDOC Command: ng generate @ngxs/store:actions Options: --name: description: The name of the actions required: Yes default_value: "" --path: description: The path to create the actions required: No default_value: App's root directory --flat: description: Boolean flag to indicate if a dir is created required: No default_value: "false" ``` -------------------------------- ### Generate NGXS Store with Default Command Source: https://github.com/ngxs/store/blob/master/tutorials/create-app/src/content/tutorial/1-create-a-todo-app/2-installation/2-create-store/content.md This command generates a basic NGXS store with default naming and path conventions. It creates action, state spec, and state files. ```bash ng generate @ngxs/store:store ``` -------------------------------- ### NGXS Plugin API Reference for Modules and Standalone API Source: https://github.com/ngxs/store/blob/master/publication/2024-06-10_announcing_ngxs_18/article.md Lists available NGXS plugins, showing their configuration methods for both the traditional Angular module-based setup and the new standalone API. Each entry provides the plugin name and its corresponding `forRoot()` method for modules and `withNgxs*Plugin()` function for standalone applications. ```APIDOC NGXS Plugins: - DevTools: Module: NgxsReduxDevtoolsPluginModule.forRoot() Standalone: withNgxsReduxDevtoolsPlugin() - Logger: Module: NgxsLoggerPluginModule.forRoot() Standalone: withNgxsLoggerPlugin() - Storage: Module: NgxsStoragePluginModule.forRoot() Standalone: withNgxsStoragePlugin() - Forms: Module: NgxsFormPluginModule.forRoot() Standalone: withNgxsFormPlugin() - Router: Module: NgxsRouterPluginModule.forRoot() Standalone: withNgxsRouterPlugin() - Web Socket: Module: NgxsWebsocketPluginModule.forRoot({url: 'ws://localhost:4200'}) Standalone: withNgxsWebSocketPlugin({url: 'ws://localhost:4200'}) ``` -------------------------------- ### Define NGXS State with Action and Context Source: https://github.com/ngxs/store/blob/master/publication/2024-06-10_announcing_ngxs_18/article.md This code defines a basic NGXS state class named 'MyState' with a default value and an 'Add' action. The action uses `StateContext` to update the state, demonstrating a typical state and action setup in NGXS. ```ts @State({ name: 'number', defaults: 0 }) @Injectable() class MyState { @Action(Add) add(ctx: StateContext, { payload }: Add) { return of({}).pipe(tap(() => ctx.setState(ctx.getState() + payload))); } } ``` -------------------------------- ### NGXS CLI Command Line Options and Plop Integration Source: https://github.com/ngxs/store/blob/master/docs/plugins/cli.md Details the various command-line options available for the NGXS CLI, including how to specify the store name, output directory, folder name, and whether to create a spec file. It also introduces the `--plopfile` option, which enables the use of custom Plop templates for advanced code generation. ```bash $ ngxs --name name --spec boolean --directory path --folder-name name $ ngxs --help ``` ```APIDOC NGXS CLI Options --name name Store name --directory path By default, the prompt is set to the current directory --folder-name name Use your own folder name, default: state --spec boolean Creates a spec file for store, default: true Custom template generator --plopfile path Path to the plopfile ``` -------------------------------- ### Configure NGXS Store with Modules vs. Standalone API Source: https://github.com/ngxs/store/blob/master/publication/2024-06-10_announcing_ngxs_18/article.md Compares the traditional module-based configuration of NGXS with the new standalone API using `provideStore` and `withNgxs*Plugin` functions, demonstrating how to register states and plugins for your NGXS store. ```typescript import { NgxsModule } from '@ngxs/store'; import { NgxsReduxDevtoolsPluginModule } from '@ngxs/devtools-plugin'; @NgModule({ imports: [ NgxsModule.forRoot([TodosState], { developmentMode: !environment.production }), NgxsReduxDevtoolsPluginModule.forRoot({ disabled: environment.production }) ] }) export class AppModule {} ``` ```typescript import { provideStore } from '@ngxs/store'; import { withNgxsReduxDevtoolsPlugin } from '@ngxs/devtools-plugin'; export const appConfig: ApplicationConfig = { providers: [ provideStore( [TodosState], { developmentMode: !environment.production }, withNgxsReduxDevtoolsPlugin({ disabled: environment.production }) ) ] }; ``` -------------------------------- ### Build NGXS Library Packages Source: https://github.com/ngxs/store/blob/master/CONTRIBUTING.md Compiles all NGXS main and plugin packages into separate npm packages, placing them in the `builds/` directory, ready for publishing or local linking. ```bash yarn build ``` -------------------------------- ### Unoptimized NGXS Selector Example Source: https://github.com/ngxs/store/blob/master/docs/concepts/select/optimizing-selectors.md An example of a selector that implicitly receives the entire state. This `getViewData` selector will recalculate every time any part of `SomeStateModel` changes, even if it only depends on `state.data`, leading to inefficient re-execution of `expensiveFunction`. ```TypeScript @Selector() static getViewData(state: SomeStateModel) { return state.data.map(d => expensiveFunction(d)); } ``` -------------------------------- ### Get Snapshot of State with Store Service in NGXS Source: https://github.com/ngxs/store/blob/master/docs/concepts/select/README.md Shows how to use `store.selectSnapshot` to get the current raw value of a state slice. This is useful for scenarios where a static value is needed, such as in an HTTP interceptor to retrieve an authentication token without subscribing to an Observable. ```typescript @Injectable() export class JWTInterceptor implements HttpInterceptor { constructor(private store: Store) {} intercept(req: HttpRequest, next: HttpHandler): Observable> { const token = this.store.selectSnapshot(AuthState.getToken); req = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }); return next.handle(req); } } ``` -------------------------------- ### NGXS State Operator: upsertItem Usage Example Source: https://github.com/ngxs/store/blob/master/docs/concepts/state/operators-1.md Demonstrates how to apply the `upsertItem` state operator within an NGXS `setState` call. This example shows updating a 'foods' array by either inserting a new 'food' item or updating an existing one based on its 'id'. ```TypeScript ctx.setState( patch({ foods: upsertItem(f => f.id === foodId, food) }) ); ``` -------------------------------- ### NGXS @Select Decorator Usage Examples Source: https://github.com/ngxs/store/blob/master/docs/concepts/select/select-decorator.md This TypeScript code demonstrates various ways to use the @Select decorator to retrieve data from the NGXS store. Examples include selecting an entire state, using a memoized selector, selecting a specific property with a function, and implicitly selecting the state based on the observable type. ```typescript import { Select } from '@ngxs/store'; import { ZooState, ZooStateModel } from './zoo.state'; @Component({ ... }) export class ZooComponent { // Reads the name of the state from the state class @Select(ZooState) animals$: Observable; // Uses the pandas memoized selector to only return pandas @Select(ZooState.pandas) pandas$: Observable; // Also accepts a function like our select method @Select(state => state.zoo.animals) animals$: Observable; // Reads the name of the state from the parameter @Select() zoo$: Observable; } ``` -------------------------------- ### Configure NGXS HMR Plugin Options Source: https://github.com/ngxs/store/blob/master/docs/plugins/hmr.md This snippet demonstrates how to initialize the NGXS HMR plugin with custom options. It shows how to set `deferTime` to control the delay before loading the old state and `autoClearLogs` to manage console output after each refresh, ensuring a clean development experience. ```ts import('@ngxs/hmr-plugin').then(plugin => { plugin .hmr(module, bootstrap, { deferTime: 100, autoClearLogs: true }) .catch((err: Error) => console.error(err)); }); ``` -------------------------------- ### Handling NGXS Dispatch Errors Example Source: https://github.com/ngxs/store/blob/master/docs/concepts/store/error-handling.md This example demonstrates how to handle errors thrown by an NGXS action at the 'dispatch' call level. It shows an 'AppState' action that throws an unhandled error, followed by two methods in an 'AppComponent' to catch these errors: using an 'error' callback in a 'subscribe' function and using 'async/await' with 'try/catch' after converting the observable to a promise. ```ts class AppState { @Action(ActionThatCausesAnError) unhandledError(ctx: StateContext) { // error is thrown } } ``` ```ts import { lastValueFrom } from 'rxjs'; class AppComponent { //... handleError() { this.store.dispatch(new ActionThatCausesAnError()).subscribe({ error: error => { console.log('unhandled error on dispatch subscription: ', error); } }); } async handleErrorAsync() { try { await lastValueFrom(this.store.dispatch(new ActionThatCausesAnError())); } catch (error) { console.log('unhandled error on dispatch caught: ', error); } } } ``` -------------------------------- ### Implement NGXS Action Collector Service Source: https://github.com/ngxs/store/blob/master/docs/recipes/unit-testing.md This TypeScript code defines `NgxsActionCollector`, an injectable service for monitoring and categorizing NGXS actions by their status (dispatched, successful, errored, cancelled, completed). It includes methods to start, stop, and reset the collection. The `provideNgxsActionCollector` function is also provided to easily integrate this service into Angular's environment providers, ensuring it starts automatically. ```typescript import { ENVIRONMENT_INITIALIZER, inject, Injectable, makeEnvironmentProviders, OnDestroy } from '@angular/core'; import { Actions, ActionStatus, ActionContext } from '@ngxs/store'; import { ReplaySubject, Subject, takeUntil } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class NgxsActionCollector implements OnDestroy { private _destroyed$ = new ReplaySubject(1); private _stopped$ = new Subject(); private _started = false; readonly dispatched: any[] = []; readonly completed: any[] = []; readonly successful: any[] = []; readonly errored: any[] = []; readonly cancelled: any[] = []; constructor(private _actions$: Actions) {} start() { if (this._started) { return; } this._started = true; this._actions$.pipe(takeUntil(this._destroyed$), takeUntil(this._stopped$)).subscribe({ next: (actionCtx: ActionContext) => { switch (actionCtx.status) { case ActionStatus.Dispatched: this.dispatched.push(actionCtx.action); break; case ActionStatus.Successful: this.successful.push(actionCtx.action); this.completed.push(actionCtx.action); break; case ActionStatus.Errored: this.errored.push(actionCtx.action); this.completed.push(actionCtx.action); break; case ActionStatus.Canceled: this.cancelled.push(actionCtx.action); this.completed.push(actionCtx.action); break; default: break; } }, complete: () => { this._started = false; }, error: () => { this._started = false; } }); } reset() { function clearArray(arr: any[]) { arr.splice(0, arr.length); } clearArray(this.dispatched); clearArray(this.completed); clearArray(this.successful); clearArray(this.errored); clearArray(this.cancelled); } stop() { this._stopped$.next(); } ngOnDestroy(): void { this._destroyed$.next(); } } export function provideNgxsActionCollector() { return makeEnvironmentProviders([ { provide: ENVIRONMENT_INITIALIZER, multi: true, useValue: () => inject(NgxsActionCollector).start() } ]); } ``` -------------------------------- ### Implement State Migrations with NGXS Storage Plugin Source: https://github.com/ngxs/store/blob/master/docs/plugins/storage.md This snippet demonstrates how to define state migration strategies using the `migrations` option in the NGXS storage plugin. It shows how to specify a version, a key, and a `migrate` function to transform old state structures to new ones during store startup. ```TypeScript export const appConfig: ApplicationConfig = { providers: [ provideStore( [], withNgxsStoragePlugin({ keys: '*', migrations: [ { version: 1, key: 'zoo', versionKey: 'myVersion', migrate: state => { return { newAnimals: state.animals, version: 2 // Important to set this to the next version! }; } } ] }) ) ] }; ``` -------------------------------- ### Integrate Dynamic NGXS Plugins into Application Configuration Source: https://github.com/ngxs/store/blob/master/docs/recipes/dynamic-plugins.md This TypeScript snippet illustrates how to import the environment-specific plugins and spread them into the `provideStore()` function within the Angular application's configuration. This ensures that only the plugins defined in the active environment file are loaded, allowing for dynamic plugin inclusion based on the build target. ```ts import { provideStore } from '@ngxs/store'; import { withNgxsRouterPlugin } from '@ngxs/router-plugin'; import { environment } from '../environments/environment'; export const appConfig: ApplicationConfig = { providers: [provideStore([], ...[withNgxsRouterPlugin(), ...environment.plugins])] } ``` -------------------------------- ### Example NGXS State Graph Structure Source: https://github.com/ngxs/store/blob/master/docs/concepts/state/sub-states.md Illustrates the hierarchical structure of a complex state graph with a 'cart' parent state and a 'saved' sub-state. ```ts { cart: { checkedout: false, items: [], saved: { dateSaved: new Date(), items: [] }; } } ``` -------------------------------- ### Dispatch NGXS Form Plugin Actions Source: https://github.com/ngxs/store/blob/master/docs/plugins/form.md Example of manually dispatching an action, `UpdateFormDirty`, to modify the form's dirty status in the NGXS store. ```ts this.store.dispatch( new UpdateFormDirty({ dirty: false, path: 'novels.newNovelForm' }) ); ``` -------------------------------- ### NGXS: Create Selector for Completed Todos Source: https://github.com/ngxs/store/blob/master/tutorials/create-app/src/content/tutorial/1-create-a-todo-app/3-get-todo-items/3-create-a-query/content.md This code snippet demonstrates how to create a Selector in the `todo.queries.ts` file. This Selector leverages `TodoSelectors.getSlices.todos` to filter and return only the Todo items marked as `completed` from the NGXS state. ```TypeScript static getCompletedTodos = createSelector( [TodoSelectors.getSlices.todos], (todos) => todos.filter((todo) => todo.completed), ); ``` -------------------------------- ### NGXS State Model for Selected Data Source: https://github.com/ngxs/store/blob/master/docs/concepts/select/optimizing-selectors.md Defines the TypeScript interface for the state model that holds an array of selected IDs, used as an example for selector optimization. ```ts interface SelectedDataStateModel { selectedIds: number[]; } ``` -------------------------------- ### Accessing signals from createSelectMap in HTML template Source: https://github.com/ngxs/store/blob/master/docs/concepts/select/signals.md Example demonstrating how to access the signals created by `createSelectMap` within an Angular HTML template. It shows accessing `invoiceId`, `invoiceSignature`, and `invoiceLines` signals. ```html

Invoice ID: {{ selectors.invoiceId() }}

Invoice signature: {{ selectors.invoiceSignature() }}

Invoice lines: {{ selectors.invoiceLines() | json }}

{{ selectors.invoiceBody() }}

``` -------------------------------- ### Provide NGXS Store with Configuration in app.config.ts Source: https://github.com/ngxs/store/blob/master/docs/concepts/store/options.md This TypeScript snippet shows how to use the `provideStore` function from `@ngxs/store` within an Angular `ApplicationConfig`. It initializes the NGXS store by passing in the defined states (assumed to be `states`) and the `ngxsConfig` object, which contains the global module options. ```typescript import { provideStore } from '@ngxs/store'; import { ngxsConfig } from './ngxs.config'; export const appConfig: ApplicationConfig = { providers: [provideStore(states, ngxsConfig)] }; ``` -------------------------------- ### NGXS Selector with No Arguments Source: https://github.com/ngxs/store/blob/master/docs/deprecations/inject-container-state-deprecation.md This example demonstrates a basic `@Selector` usage within a state class where no arguments are passed to the decorator. This pattern remains unaffected by the `injectContainerState` deprecation. ```TypeScript export class InvoiceState { @Selector() static getInvoiceId(state: InvoiceStateModel) { return state.id; } } ``` -------------------------------- ### NGXS Store Schematic Command Options (APIDOC) Source: https://github.com/ngxs/store/blob/master/docs/concepts/store/schematics.md Reference for the command-line options available when generating an NGXS store. Each option controls specific aspects of the store generation, such as naming, file location, and test file creation. ```APIDOC ng generate @ngxs/store:store options: --name: Description: The name of the store Required: Yes Default Value: (None) --path: Description: The path to create the store Required: No Default Value: App's root directory --spec: Description: Boolean flag to indicate if a unit test file should be created Required: No Default Value: true --flat: Description: Boolean flag to indicate if a dir is created Required: No Default Value: false --project: Description: Name of the project as it is defined in your angular.json Required: No Default Value: Workspace's default project ``` -------------------------------- ### Accessing NGXS State Properties with Generated Selectors Source: https://github.com/ngxs/store/blob/master/publication/2023-03-20_announcing_ngxs_3_8/article.md Provides an example of how to use the selectors generated by `createPropertySelectors` to easily access specific properties from the NGXS store, leveraging the `props` object. ```TypeScript const todos$ = this.store.select(TodoSelectors.props.todos); const loading$ = this.store.select(TodoSelectors.props.loading); const error$ = this.store.select(TodoSelectors.props.error); ``` -------------------------------- ### Configure Ngxs WebSocket Plugin with NgxsModule (Module-based) Source: https://github.com/ngxs/store/blob/master/docs/plugins/websocket.md Example of configuring the Ngxs WebSocket plugin in an Angular application using `NgxsModule` for module-based applications, specifying the WebSocket URL. ```typescript import { NgxsModule } from '@ngxs/store'; import { NgxsWebSocketPluginModule } from '@ngxs/websocket-plugin'; @NgModule({ imports: [ NgxsModule.forRoot([]), NgxsWebSocketPluginModule.forRoot({ url: 'ws://localhost:4200' }) ] }) export class AppModule {} ``` -------------------------------- ### Preparing NGXS State for Tests Using `store.reset` Source: https://github.com/ngxs/store/blob/master/docs/recipes/unit-testing.md This snippet demonstrates how to prepare the NGXS store with a specific initial state before running tests. It uses `store.reset` to set up a desired state, emphasizing the importance of merging with the current snapshot to avoid data loss and providing the registered state name as the key. ```ts import { TestBed } from '@angular/core/testing'; import { provideStore, Store } from '@ngxs/store'; import { ZooState } from './zoo.state'; import { FeedAnimals } from './zoo.actions'; export const SOME_DESIRED_STATE = { animals: ['Panda'] }; describe('Zoo', () => { let store: Store; beforeEach(() => { TestBed.configureTestingModule({ providers: [provideStore([ZooState])] }); store = TestBed.inject(Store); store.reset({ ...store.snapshot(), zoo: SOME_DESIRED_STATE }); }); it('it toggles feed', () => { store.dispatch(new FeedAnimals()); const feed = store.selectSnapshot(ZooState.getFeed); expect(feed).toBe(true); }); }); ``` -------------------------------- ### NGXS Storage Plugin Options Source: https://github.com/ngxs/store/blob/master/docs/plugins/storage.md Detailed documentation of the configurable options available for the NGXS Storage Plugin, including `keys`, `namespace`, `storage`, `deserialize`, `serialize`, `migrations`, `beforeSerialize`, and `afterDeserialize`. ```APIDOC NgxsStoragePluginOptions: keys: string | string[] Description: State name(s) to be persisted. Can be an array of strings, deeply nested via dot notation. If not provided, '*' must be explicitly specified. namespace: string Description: Used to prefix the key for the state slice, preventing conflicts in micro frontend applications. storage: StorageEngine Description: Storage strategy to use. Defaults to LocalStorage. Can be SessionStorage or any object implementing the StorageEngine API. deserialize: (value: string) => any Description: Custom deserializer function. Defaults to JSON.parse. serialize: (value: any) => string Description: Custom serializer function. Defaults to JSON.stringify. migrations: MigrationStrategy[] Description: Array of migration strategies. beforeSerialize: (state: any) => any Description: Interceptor function executed before serialization. afterDeserialize: (state: any) => any Description: Interceptor function executed after deserialization. ``` -------------------------------- ### Define an NGXS State with constructor dependency injection Source: https://github.com/ngxs/store/blob/master/docs/concepts/state/README.md This example illustrates how an NGXS state class can participate in dependency injection. Dependencies, like `ZooService`, are injected through the constructor, making them available within the state. ```TypeScript @State({ name: 'zoo', defaults: { feed: false } }) @Injectable() export class ZooState { constructor(private zooService: ZooService) {} } ```