### Install Redux and Angular Redux Store Packages Source: https://github.com/angular-redux/platform/blob/master/docs/store/README.md Installs the core Redux library and the @angular-redux/store package as peer dependencies required for Redux integration in Angular. ```sh npm install --save redux @angular-redux/store ``` -------------------------------- ### Install Angular Redux Store and Redux Source: https://github.com/angular-redux/platform/blob/master/packages/store/articles/quickstart.md Installs the `@angular-redux/store` package and its peer dependency `redux` using npm. This is the first step to set up the library in your project. ```sh npm install --save redux @angular-redux/store ``` -------------------------------- ### Bootstrap Angular Application Module Source: https://github.com/angular-redux/platform/blob/master/docs/store/README.md Standard Angular application bootstrapping process, using platformBrowserDynamic to launch the root application module. ```typescript import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './containers/app.module'; platformBrowserDynamic().bootstrapModule(AppModule); ``` -------------------------------- ### Local Development and Testing Workflow for angular-redux/store Source: https://github.com/angular-redux/platform/blob/master/packages/store/README.md This snippet details the step-by-step process for testing local modifications within the angular-redux/store project. It includes running unit tests, linting, setting up a local example application, packaging the local library, installing it into the example app, and serving the application with AoT compilation. ```Shell # 1. Run unit tests npm test # 2. Run the linter npm run lint # 3. Clone the example application git clone https://github.com/angular-redux/example-app.git # 4. Generate a 'local package' (run from your angular-redux/store clone directory) npm pack # 5. Hook your 'local package' up to your example-app (run from your example-app clone directory) npm install --save /path/to/the/tgz/file/from/above # 6. Run the example app with AoT compilation (run from your example-app clone directory) ng serve --aot ``` -------------------------------- ### Bootstrap Angular Workspace Dependencies with Yarn Source: https://github.com/angular-redux/platform/blob/master/packages/example-app/README.md Before running the application, execute this command to install and link all workspace dependencies managed by Yarn. This ensures all required packages are available for development. ```shell yarn bootstrap ``` -------------------------------- ### Install Angular CLI and create new project Source: https://github.com/angular-redux/platform/blob/master/packages/store/articles/intro-tutorial.md Installs Angular CLI globally, generates a new Angular application named 'angular-redux-quickstart', navigates into the project directory, and serves the application locally. ```sh npm install -g @angular/cli ng new angular-redux-quickstart cd angular-redux-quickstart ng serve ``` -------------------------------- ### Install Angular CLI and Create New Project Source: https://github.com/angular-redux/platform/blob/master/docs/store/articles/intro-tutorial.md This snippet demonstrates how to install the Angular CLI globally, create a new Angular application named 'angular-redux-quickstart', navigate into its directory, and serve the application locally for development. ```sh npm install -g @angular/cli ng new angular-redux-quickstart cd angular-redux-quickstart ng serve ``` -------------------------------- ### Install Redux and Angular-Redux Store Packages Source: https://github.com/angular-redux/platform/blob/master/docs/store/articles/intro-tutorial.md This command installs the 'redux' library for state management and '@angular-redux/store', which provides Redux bindings specifically designed for Angular applications, into the current project. ```sh npm install redux @angular-redux/store ``` -------------------------------- ### Install Redux and Angular Redux store packages Source: https://github.com/angular-redux/platform/blob/master/packages/store/articles/intro-tutorial.md Installs the core Redux library and the @angular-redux/store bindings, which provide Redux integration for Angular applications, as project dependencies. ```sh npm install redux @angular-redux/store ``` -------------------------------- ### Provide Existing Redux Store to NgRedux Source: https://github.com/angular-redux/platform/blob/master/docs/store/README.md Illustrates an alternative method to integrate Redux by manually creating the Redux store using createStore and then providing it to NgRedux via the provideStore() function. This allows for more granular control over store creation and middleware application. ```typescript import { applyMiddleware, Store, combineReducers, compose, createStore, } from 'redux'; import { NgReduxModule, NgRedux } from '@angular-redux/store'; import { createLogger } from 'redux-logger'; import { rootReducer } from './reducers'; interface IAppState { /* ... */ } export const store: Store = createStore( rootReducer, applyMiddleware(createLogger()), ); @NgModule({ /* ... */ imports: [, /* ... */ NgReduxModule], }) class AppModule { constructor(ngRedux: NgRedux) { ngRedux.provideStore(store); } } ``` -------------------------------- ### Install Angular Redux Router Bindings Source: https://github.com/angular-redux/platform/blob/master/docs/router/README.md This command installs the @angular-redux/router package using npm and saves it as a dependency in your project's package.json. ```Shell npm install @angular-redux/router --save ``` -------------------------------- ### Bootstrap Angular Application with Platform Browser Dynamic Source: https://github.com/angular-redux/platform/blob/master/packages/store/articles/quickstart.md Bootstraps the main Angular application module (`AppModule`) using `platformBrowserDynamic`. This is a standard Angular setup for browser-based applications. ```typescript import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './containers/app.module'; platformBrowserDynamic().bootstrapModule(AppModule); ``` -------------------------------- ### Angular Module Setup with NgReduxModule Source: https://github.com/angular-redux/platform/blob/master/packages/form/README.md Provides an example of an Angular module configuration that integrates `@angular-redux/form` and `@angular-redux/store` (NgReduxModule). This setup is used when `@angular-redux/store` is already part of the project. ```typescript import { NgReduxModule } from '@angular-redux/store'; import { NgReduxFormModule } from '@angular-redux/form'; @NgModule({ imports: [ BrowserModule, ReactiveFormsModule, FormsModule, NgReduxFormModule, NgReduxModule, ], bootstrap: [MyApplicationComponent], }) export class ExampleModule {} ``` -------------------------------- ### Configure Redux Store with NgReduxModule in Angular Source: https://github.com/angular-redux/platform/blob/master/docs/store/README.md Demonstrates how to import NgReduxModule into your Angular application module and configure the Redux store using ngRedux.configureStore. This setup includes defining the root reducer, initial state, and optionally applying Redux middlewares like redux-logger. ```typescript import { NgReduxModule, NgRedux } from '@angular-redux/store'; import { createLogger } from 'redux-logger'; import { rootReducer } from './reducers'; interface IAppState { /* ... */ } @NgModule({ /* ... */ imports: [, /* ... */ NgReduxModule], }) export class AppModule { constructor(ngRedux: NgRedux) { ngRedux.configureStore(rootReducer, {}, [createLogger()]); } } ``` -------------------------------- ### Run Angular Development Server Source: https://github.com/angular-redux/platform/blob/master/packages/example-app/README.md Starts a local development server for the Angular application, typically accessible at `http://localhost:4200/`. The application will automatically reload in the browser upon changes to source files, facilitating rapid development. ```shell ng serve ``` -------------------------------- ### Install @angular-redux/store and Redux Source: https://github.com/angular-redux/platform/blob/master/packages/store/README.md Installs the `@angular-redux/store` package along with its peer dependency, Redux, using npm. This command adds both packages to your project's dependencies. ```Shell npm install --save redux @angular-redux/store ``` -------------------------------- ### Build Angular Project for Deployment Source: https://github.com/angular-redux/platform/blob/master/packages/example-app/README.md Compiles the Angular application into deployable artifacts, which are stored in the `dist/` directory. Use the `-prod` flag to create an optimized production build, including minification and tree-shaking. ```shell ng build ``` -------------------------------- ### Provide Pre-existing Redux Store to Angular AppModule Source: https://github.com/angular-redux/platform/blob/master/packages/store/articles/quickstart.md Shows an alternative way to integrate Redux by creating the store manually using `createStore` from the `redux` library. The pre-existing store is then provided to `NgRedux` via the `ngRedux.provideStore()` method. ```typescript import { applyMiddleware, Store, combineReducers, compose, createStore, } from 'redux'; import { NgReduxModule, NgRedux } from '@angular-redux/store'; import { createLogger } => 'redux-logger'; import { rootReducer } from './reducers'; interface IAppState { /* ... */ } export const store: Store = createStore( rootReducer, applyMiddleware(createLogger()), ); @NgModule({ /* ... */ imports: [, /* ... */ NgReduxModule], }) class AppModule { constructor(ngRedux: NgRedux) { ngRedux.provideStore(store); } } ``` -------------------------------- ### Install @angular-redux/router via npm Source: https://github.com/angular-redux/platform/blob/master/packages/router/README.md Installs the @angular-redux/router package and saves it as a dependency in your project's package.json file. ```bash npm install @angular-redux/router --save ``` -------------------------------- ### Install Angular Redux canary build with npm Source: https://github.com/angular-redux/platform/blob/master/CONTRIBUTING.md Install the latest canary build of an Angular Redux package using npm. Replace '@angular-redux/store' with the specific package you intend to use. ```bash npm install @angular-redux/store@canary ``` -------------------------------- ### Access Redux State and Dispatch Actions in Angular Components Source: https://github.com/angular-redux/platform/blob/master/docs/store/README.md Shows how to use the @select decorator to access slices of the Redux store state as RxJS Observables, which efficiently integrate with Angular's change detection. It also demonstrates dispatching actions to the Redux store using the ngRedux.dispatch() method from within an Angular component. ```typescript import { select } from '@angular-redux/store'; @Component({ template: '', }) class App { @select() count$: Observable; constructor(private ngRedux: NgRedux) {} onClick() { this.ngRedux.dispatch({ type: INCREMENT }); } } ``` -------------------------------- ### Execute Angular Unit Tests with Karma Source: https://github.com/angular-redux/platform/blob/master/packages/example-app/README.md Runs the unit tests for the Angular project using Karma, a test runner. This command helps ensure individual components and services function as expected. ```shell ng test ``` -------------------------------- ### Docsify Configuration for Angular Redux Project Source: https://github.com/angular-redux/platform/blob/master/docs/index.html This JavaScript snippet initializes the global Docsify configuration object, setting up the documentation site's name, GitHub repository link, enabling navbar loading, defining the date format for updates, and specifying the theme color. ```JavaScript window.$docsify = { name: 'Angular Redux', repo: 'angular-redux/platform', loadNavbar: true, formatUpdated: '{MM}/{DD} {HH}:{mm}', themeColor: '#D1472F', } ``` -------------------------------- ### Angular Module Setup with provideReduxForms for Direct Redux Store Source: https://github.com/angular-redux/platform/blob/master/packages/form/README.md Illustrates an Angular module setup for `@angular-redux/form` when using a direct Redux store instance, without `@angular-redux/store`. It shows how to provide the Redux store using `provideReduxForms`. ```typescript import { provideReduxForms } from '@angular-redux/form'; const storeCreator = compose(applyMiddleware(logger))(createStore); const store = create(reducers, {}); @NgModule({ imports: [BrowserModule, ReactiveFormsModule, FormsModule, NgReduxFormModule], providers: [provideReduxForms(store)], bootstrap: [MyApplicationComponent], }) export class ExampleModule {} ``` -------------------------------- ### Configure Angular Module with NgReduxFormModule and NgReduxModule Source: https://github.com/angular-redux/platform/blob/master/docs/form/README.md Provides an example of an Angular module configuration that integrates '@angular-redux/form' along with '@angular-redux/store' (NgReduxModule). This setup is used when '@angular-redux/store' is already part of the project. ```TypeScript import { NgReduxModule } from '@angular-redux/store'; import { NgReduxFormModule } from '@angular-redux/form'; @NgModule({ imports: [ BrowserModule, ReactiveFormsModule, FormsModule, NgReduxFormModule, NgReduxModule, ], bootstrap: [MyApplicationComponent], }) export class ExampleModule {} ``` -------------------------------- ### Install Flux Standard Action (FSA) for Redux Source: https://github.com/angular-redux/platform/blob/master/packages/store/articles/strongly-typed-reducers.md Provides the npm command to install `flux-standard-action`, a widely-used convention for defining the shape of actions in Redux. FSAs include 'payload' and 'error' parameters in addition to the basic 'type'. ```sh npm install --save flux-standard-action ``` -------------------------------- ### Example Redux Store State Structure Source: https://github.com/angular-redux/platform/blob/master/packages/store/articles/fractal-store.md Illustrates a sample Redux store state structure with nested user data, demonstrating the kind of state that fractal stores can operate on. Each user has a name, occupation, and lines of code (loc). ```typescript { users: { bob: { name: 'Bob Smith', occupation: 'Programmer', loc: 1023 }, alice: { name: 'Alice Jones', occupation: 'DevOps Specialist', loc: 2314 } } } ``` -------------------------------- ### Generate Angular Components, Directives, Pipes, Services, Modules Source: https://github.com/angular-redux/platform/blob/master/packages/example-app/README.md Use the Angular CLI to quickly generate new components, directives, pipes, services, classes, or modules. This command streamlines the creation of common Angular building blocks, following best practices. ```shell ng generate component component-name ``` -------------------------------- ### Selecting Redux Store Data with ngRedux.select() Function Source: https://github.com/angular-redux/platform/blob/master/docs/store/README.md For those preferring RxJS over decorators, the ngRedux.select() function provides an alternative to select store data. It can take a property name or a function to transform a property, and being an observable, it fully supports RxJS operators like .map and .filter for further data manipulation. ```typescript import { Component } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Counter } from '../components/Counter'; import * as CounterActions from '../actions/CounterActions'; import { NgRedux } from '@angular-redux/store'; interface IAppState { counter: number; } @Component({ selector: 'root', template: ` `, }) export class Counter { private count$: Observable; constructor(private ngRedux: NgRedux) {} ngOnInit() { let { increment, decrement } = CounterActions; this.counter$ = this.ngRedux.select('counter'); } incrementIfOdd = () => this.ngRedux.dispatch(CounterActions.incrementIfOdd()); incrementAsync = () => this.ngRedux.dispatch(CounterActions.incrementAsync()); } ``` -------------------------------- ### Example Redux State Structure for Form Binding Source: https://github.com/angular-redux/platform/blob/master/packages/form/README.md Illustrates a sample Redux application state structure, showing how form data (e.g., 'address') would be nested under a specific key ('myForm') that corresponds to the `connect` directive's argument. ```json { "foo": "bar", "myForm": { "address": "1 Foo St." } } ``` -------------------------------- ### Unit Testing Angular Redux Action Dispatches with Jasmine Spies Source: https://github.com/angular-redux/platform/blob/master/packages/store/articles/intro-tutorial.md This example demonstrates how to verify action dispatches in unit tests using Jasmine spies. By spying on `MockNgRedux.mockInstance.dispatch`, you can assert that specific actions are dispatched when your component's methods are invoked, ensuring correct interaction with the Redux store. ```TypeScript it('dispatches INCREMENT when ...', () => { const spy = spyOn(MockNgRedux.mockInstance, 'dispatch'); // Run your test code ... // Perform your expectations expect(spy).toHaveBeenCalledWith({ type: CounterActions.INCREMENT }); // ... etc. }); ``` -------------------------------- ### Define IAppState Interface for Redux Store Source: https://github.com/angular-redux/platform/blob/master/docs/store/articles/intro-tutorial.md This TypeScript snippet defines the `IAppState` interface, which represents the structure of the application's state in a Redux store. For this simple counter example, it contains a single property: `count` of type `number`. ```typescript interface IAppState { count: number; } ``` -------------------------------- ### Unit Testing Redux Action Dispatches with Jasmine Spies Source: https://github.com/angular-redux/platform/blob/master/docs/store/articles/intro-tutorial.md This snippet provides an example of unit testing Redux action dispatches in an Angular component. It utilizes Jasmine spies on `MockNgRedux.mockInstance.dispatch` to verify that specific actions are dispatched when component methods are invoked, ensuring the correct interaction with the Redux store. ```typescript it('dispatches INCREMENT when ...', () => { const spy = spyOn(MockNgRedux.mockInstance, 'dispatch'); // Run your test code ... // Perform your expectations expect(spy).toHaveBeenCalledWith({ type: CounterActions.INCREMENT }); // ... etc. }); ``` -------------------------------- ### Configure Redux Store in Angular AppModule using NgRedux Source: https://github.com/angular-redux/platform/blob/master/packages/store/articles/quickstart.md Demonstrates how to import `NgReduxModule` and configure the Redux store within the `AppModule` constructor using `ngRedux.configureStore()`. This method allows direct configuration of reducers, initial state, and middlewares like `redux-logger`. ```typescript import { NgReduxModule, NgRedux } from '@angular-redux/store'; import { createLogger } from 'redux-logger'; import { rootReducer } from './reducers'; interface IAppState { /* ... */ } @NgModule({ /* ... */ imports: [, /* ... */ NgReduxModule], }) export class AppModule { constructor(ngRedux: NgRedux) { ngRedux.configureStore(rootReducer, {}, [createLogger()]); } } ``` -------------------------------- ### Example Redux State Structure for Angular Form Source: https://github.com/angular-redux/platform/blob/master/docs/form/README.md Illustrates a sample Redux state object, showing how form data (e.g., 'myForm') would be structured within the overall application state. This structure corresponds to the path provided to the 'connect' directive. ```JSON { "foo": "bar", "myForm": { "address": "1 Foo St." } } ``` -------------------------------- ### Execute Angular End-to-End Tests with Protractor Source: https://github.com/angular-redux/platform/blob/master/packages/example-app/README.md Runs end-to-end tests for the Angular application using Protractor. These tests simulate user interactions to verify the entire application flow. Ensure the app is served via `ng serve` before execution. ```shell ng e2e ``` -------------------------------- ### Using @select decorator for state selection in Angular-Redux Source: https://github.com/angular-redux/platform/blob/master/packages/store/articles/select-pattern.md Demonstrates various ways to use the `@select` decorator to observe Redux store values. It shows selection by property name (implicit and explicit string), by path array, and by a selector function, including a transformation example. ```TypeScript import { Component } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { select } from '@angular-redux/store'; @Component({ selector: 'counter-value-printed-many-times', template: `

{{ counter$ | async }}

{{ counter | async }}

{{ counterSelectedWithString | async }}

{{ counterSelectedWithFunction | async }}

{{ counterSelectedWithFunctionAndMultipliedByTwo | async }}

`, }) export class CounterValue { // this selects `counter` from the store and attaches it to this property // it uses the property name to select, and ignores the $ from it @select() counter$; // this selects `counter` from the store and attaches it to this property @select() counter; // this selects `counter` from the store and attaches it to this property @select('counter') counterSelectedWithString; // this selects `pathDemo.foo.bar` from the store and attaches it to this // property. @select(['pathDemo', 'foo', 'bar']) pathSelection; // this selects `counter` from the store and attaches it to this property @select(state => state.counter) counterSelectedWithFunction; // this selects `counter` from the store and multiples it by two @select(state => state.counter * 2) counterSelectedWithFuntionAndMultipliedByTwo: Observable; } ``` -------------------------------- ### HTML Form Structure Matching Redux State Source: https://github.com/angular-redux/platform/blob/master/packages/form/README.md Provides an example of an HTML form that would produce the corresponding JSON payload shown previously, demonstrating how form input names and nested forms map to the Redux state structure. ```html
``` -------------------------------- ### Using @select with ImmutableJS in @angular-redux/store 3.3.0+ Source: https://github.com/angular-redux/platform/blob/master/packages/store/articles/immutable-js.md This example demonstrates the enhanced @select decorator in @angular-redux/store version 3.3.0 and later. It shows how developers can now use declarative path selectors with ImmutableJS objects, combining the syntactic convenience of raw objects with the mutation safety provided by ImmutableJS. ```typescript // Path selector @select(['counts', 'firstCount']) firstCount$: Observable; // Selecting an immutable object @select() counts$: Observable>; constructor() { this.counts$.map(counts: Map => { // Correct: we are forced into the non-mutating approach. return counts.get('firstCount') + 1; }); } ``` -------------------------------- ### NgControl Path for Simple Form Input Source: https://github.com/angular-redux/platform/blob/master/docs/form/README.md This example shows the computed 'path' array for a simple 'fullname' input field within the 'form1' connected form. It illustrates how Angular determines the location in the Redux state for a basic form control. ```text ['form1', 'fullname'] ``` -------------------------------- ### Access Redux State and Dispatch Actions in Angular Components Source: https://github.com/angular-redux/platform/blob/master/packages/store/articles/quickstart.md Illustrates how to use the `@select` decorator to access Redux store state as an Observable within an Angular component. It also demonstrates how to dispatch actions using the `ngRedux.dispatch()` method to modify the store state. ```typescript import { select } from '@angular-redux/store'; @Component({ template: '', }) class App { @select() count$: Observable; constructor(private ngRedux: NgRedux) {} onClick() { this.ngRedux.dispatch({ type: INCREMENT }); } } ``` -------------------------------- ### NgControl Path for Array Element Source: https://github.com/angular-redux/platform/blob/master/docs/form/README.md This example shows the computed 'path' array for an element within the 'dependents' array, including the zero-based index. It demonstrates how Angular navigates and identifies controls within nested array structures. ```text ['form1', 'dependents', 0] ``` -------------------------------- ### Displaying Asynchronous Data in Angular Template Source: https://github.com/angular-redux/platform/blob/master/packages/example-app/src/app/animals/animal/component.html This snippet illustrates the use of Angular's `async` pipe to subscribe to and display the latest values from observables directly within the template. It automatically handles subscription and unsubscription, preventing memory leaks and simplifying data binding for asynchronous streams like those from NgRx or other state management solutions. ```Angular Template {{ name | async }} {{ ticketPrice | async }} ${{ subTotal | async }} ``` -------------------------------- ### Integrate Angular Redux Router into Root Module Source: https://github.com/angular-redux/platform/blob/master/docs/router/README.md This TypeScript code shows how to add @angular-redux/router bindings to your Angular root module. It imports necessary modules, configures RouterModule and NgReduxRouterModule, and initializes NgRedux and NgReduxRouter in the module's constructor. ```TypeScript import { NgModule } from '@angular/core'; import { NgReduxModule, NgRedux } from '@angular-redux/core'; import { NgReduxRouterModule, NgReduxRouter } from '@angular-redux/router'; import { RouterModule } from '@angular/router'; import { routes } from './routes'; @NgModule({ imports: [ RouterModule.forRoot(routes), NgReduxModule, NgReduxRouterModule.forRoot(), // ...your imports ], // Other stuff.. }) export class AppModule { constructor(ngRedux: NgRedux, ngReduxRouter: NgReduxRouter) { ngRedux.configureStore(/* args */); ngReduxRouter.initialize(/* args */); } } ``` -------------------------------- ### Using @select Decorator for Simple Angular Redux Store Selection Source: https://github.com/angular-redux/platform/blob/master/packages/store/articles/intro-tutorial.md The `@select` decorator provides a shorthand for selecting store properties, simplifying component code compared to `ngRedux.select` for basic cases. This example demonstrates its usage to bind a component property directly to an Observable of a store slice with the same name. ```TypeScript import { Component } from '@angular/core'; import { NgRedux, select } from '@angular-redux/store'; import { CounterActions } from './app.actions'; import { IAppState } from '../store'; import { Observable } from 'rxjs/Observable'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { title = 'app works!'; @select() readonly count$: Observable; constructor( private actions: CounterActions, private ngRedux: NgRedux, ) {} increment() { this.ngRedux.dispatch(this.actions.increment()); } decrement() { this.ngRedux.dispatch(this.actions.decrement()); } } ``` -------------------------------- ### Implementing Flux Standard Actions (FSA) in Redux with TypeScript Source: https://github.com/angular-redux/platform/blob/master/docs/store/articles/cookbooks.md This section explains how to adopt the Flux Standard Action (FSA) convention for defining action shapes, which includes 'payload' and 'error' parameters. It demonstrates how to install the `flux-standard-action` package and use its `Action` type with generic payload types to strengthen reducer typings, including union types for flexible payloads. ```shell npm install --save flux-standard-action ``` ```typescript import { Reducer } from 'redux'; import { Action } from 'flux-standard-action'; export const fooReducer: Reducer = ( state: TFoo, action: Action, ): TFoo => { // ... }; ``` ```typescript export const barReducer: Reducer = ( state: IBar, action: Action, ): IBar => { switch (action.type) { case A_HAS_CHANGED: return Object.assign({}, state, { a: action.payload, }); case B_HAS_CHANGED: return Object.assign({}, state, { b: action.payload, }); // ... } }; ``` -------------------------------- ### Simplify Redux Store Selection with @select Decorator in Angular Source: https://github.com/angular-redux/platform/blob/master/docs/store/articles/intro-tutorial.md This snippet demonstrates how to refactor an Angular component to use the `@select` decorator from `@angular-redux/store`. It simplifies the selection of Redux store properties into an Observable, replacing `ngRedux.select` for simple cases. The example shows importing `@select` and decorating a component property to automatically bind to a store slice with the same name. ```typescript import { Component } from '@angular/core'; import { NgRedux, select } from '@angular-redux/store'; // <- Changed import { CounterActions } from './app.actions'; import { IAppState } from '../store'; import { Observable } from 'rxjs/Observable'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app works!'; @select() readonly count$: Observable; // <- Changed constructor( private actions: CounterActions, private ngRedux: NgRedux ) {} // <- Changed increment() { this.ngRedux.dispatch(this.actions.increment()); } decrement() { this.ngRedux.dispatch(this.actions.decrement()); } } ``` -------------------------------- ### Configure Angular Redux Store with Redux-Observable Epic Middleware Source: https://github.com/angular-redux/platform/blob/master/packages/store/articles/epics.md This TypeScript code demonstrates how to configure the Angular `AppModule` to integrate `redux-observable` epics. It imports `NgReduxModule`, provides `SessionEpics` as a service, and uses `createEpicMiddleware` to add the `login` epic to the Redux store's middleware. This setup ensures that dispatched actions can trigger the defined side-effects. ```typescript import { NgModule } from '@angular/core'; import { NgReduxModule, NgRedux } from '@angular-redux/store'; import { createEpicMiddleware } from 'redux-observable'; import rootReducer from './reducers'; import { SessionEpics } from './epics'; @NgModule({ /* ... */ imports: [, /* ... */ NgReduxModule], providers: [ SessionEpics, /* ... */ ], }) export class AppModule { constructor( private ngRedux: NgRedux, private epics: SessionEpics, ) { const middleware = [createEpicMiddleware(this.epics.login)]; ngRedux.configureStore(rootReducer, {}, middleware); } } ``` -------------------------------- ### Reducer Concept Analogy with Array.prototype.reduce Pseudocode Source: https://github.com/angular-redux/platform/blob/master/docs/store/articles/intro-tutorial.md Explains the reducer concept using an analogy to `Array.prototype.reduce`, showing how a stream of actions is reduced over time to yield the final application state. ```typescript // Pseudocode const finalAppState: IAppState = actionsOverTime.reduce( rootReducer, INITIAL_STATE, ); ``` -------------------------------- ### Example HTML Form Structure for Angular-Redux Source: https://github.com/angular-redux/platform/blob/master/docs/form/README.md This HTML snippet demonstrates a form structure that would produce the JSON payload shown previously. It uses `connect` on the main form and `ngControl`, `ngModel` on inputs, along with nested forms for grouping related inputs. The `name` attributes on inputs and form groups directly correspond to the keys in the `action.payload.value` object. ```HTML
``` -------------------------------- ### Conceptual Reducer Logic with JavaScript Pseudocode Source: https://github.com/angular-redux/platform/blob/master/docs/store/articles/intro-tutorial.md Illustrates the core concept of a Redux reducer, showing how a stream of actions reduces to a new state based on action types (INCREMENT/DECREMENT). ```javascript // Pseudocode const nextValueOfCount = streamOfActions.reduce( (currentValueOfCount, action) => { switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; } return state; }, { count: 0 }, ); ``` -------------------------------- ### Applying Observable Chains with @select$ Decorator Source: https://github.com/angular-redux/platform/blob/master/docs/store/README.md The @select$ decorator extends the functionality of @select by allowing developers to specify observable chains that execute on the selected result. This enables advanced data transformations and reactive patterns directly within the decorator, such as debouncing or mapping values. ```typescript import { select$ } from 'angular-redux/store'; export const debounceAndTriple = obs$ => obs$.debounce(300).map(x => 3 * x); class Foo { @select$(['foo', 'bar'], debounceAndTriple) readonly debouncedFooBar$: Observable; } ``` -------------------------------- ### Reducer Concept for Next State Calculation Pseudocode Source: https://github.com/angular-redux/platform/blob/master/docs/store/articles/intro-tutorial.md Simplifies the reducer concept to show how the `rootReducer` computes the `nextState` from the `lastState` and `mostRecentAction`, followed by UI rendering. ```typescript // Pseudocode const nextState = rootReducer(lastState, mostRecentAction); UI.render(nextState); ``` -------------------------------- ### Bootstrap Angular Application with Redux Source: https://github.com/angular-redux/platform/blob/master/packages/store/README.md Initializes and bootstraps an Angular application using `platformBrowserDynamic` and the root `AppModule`, which will later be configured with Redux. ```typescript import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './containers/app.module'; platformBrowserDynamic().bootstrapModule(AppModule); ``` -------------------------------- ### Using @select Decorator for Redux Store Selection in Angular Source: https://github.com/angular-redux/platform/blob/master/docs/store/README.md The @select decorator transforms a class property into an observable that observes a Redux Store value. It supports various parameters: a string for direct property matching, an array of strings for path-based selection, a function for custom RxJs selectors, or no parameter to use the property's name (ignoring '$' characters). ```typescript import { Component } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { select } from '@angular-redux/store'; @Component({ selector: 'counter-value-printed-many-times', template: `

{{ counter$ | async }}

{{ counter | async }}

{{ counterSelectedWithString | async }}

{{ counterSelectedWithFunction | async }}

{{ counterSelectedWithFunctionAndMultipliedByTwo | async }}

`, }) export class CounterValue { // this selects `counter` from the store and attaches it to this property // it uses the property name to select, and ignores the $ from it @select() counter$; // this selects `counter` from the store and attaches it to this property @select() counter; // this selects `counter` from the store and attaches it to this property @select('counter') counterSelectedWithString; // this selects `pathDemo.foo.bar` from the store and attaches it to this // property. @select(['pathDemo', 'foo', 'bar']) pathSelection; // this selects `counter` from the store and attaches it to this property @select(state => state.counter) counterSelectedWithFunction; // this selects `counter` from the store and multiples it by two @select(state => state.counter * 2) counterSelectedWithFuntionAndMultipliedByTwo: Observable; } ``` -------------------------------- ### Implementing Redux Root Reducer and Initial State in TypeScript Source: https://github.com/angular-redux/platform/blob/master/packages/store/articles/intro-tutorial.md This TypeScript file defines the application's state interface `IAppState`, the `INITIAL_STATE`, and the `rootReducer` function. The `rootReducer` takes the current state and an action, then returns a new state based on the action type, demonstrating how state transitions are handled immutably. ```typescript import { Action } from 'redux'; import { CounterActions } from './app/app.actions'; export interface IAppState { count: number; } export const INITIAL_STATE: IAppState = { count: 0, }; export function rootReducer(lastState: IAppState, action: Action): IAppState { switch (action.type) { case CounterActions.INCREMENT: return { count: lastState.count + 1 }; case CounterActions.DECREMENT: return { count: lastState.count - 1 }; } // We don't care about any other actions right now. return lastState; } ``` -------------------------------- ### Configuring Redux Store in Angular AppModule with NgRedux Source: https://github.com/angular-redux/platform/blob/master/docs/store/articles/intro-tutorial.md Demonstrates how to integrate the Redux store into an Angular application's `AppModule`. It imports the `rootReducer`, `IAppState`, `INITIAL_STATE`, and `CounterActions`, then uses `NgRedux.configureStore` in the constructor to set up the Redux store. ```typescript // ... imports as above import { rootReducer, IAppState, INITIAL_STATE } from '../store'; // < New import { CounterActions } from './app/app.actions'; // <- New @NgModule({ declarations: [AppComponent], imports: [BrowserModule, FormsModule, HttpModule, NgReduxModule], providers: [CounterActions], // <- New bootstrap: [AppComponent], }) export class AppModule { constructor(ngRedux: NgRedux) { // Tell @angular-redux/store about our rootReducer and our initial state. // It will use this to create a redux store for us and wire up all the // events. ngRedux.configureStore(rootReducer, INITIAL_STATE); } } ``` -------------------------------- ### Provide Existing Redux Store to NgRedux Source: https://github.com/angular-redux/platform/blob/master/packages/store/README.md Illustrates an alternative method to integrate Redux by creating the Redux store manually using `createStore` and then providing this pre-configured store to `NgRedux` using the `provideStore()` method. This allows for more granular control over store creation. ```typescript import { applyMiddleware, Store, combineReducers, compose, createStore, } from 'redux'; import { NgReduxModule, NgRedux } from '@angular-redux/store'; import { createLogger } from 'redux-logger'; import { rootReducer } from './reducers'; interface IAppState { /* ... */ } export const store: Store = createStore( rootReducer, applyMiddleware(createLogger()), ); @NgModule({ /* ... */ imports: [, /* ... */ NgReduxModule], }) class AppModule { constructor(ngRedux: NgRedux) { ngRedux.provideStore(store); } } ``` -------------------------------- ### Example Structure of Form Values Payload Source: https://github.com/angular-redux/platform/blob/master/docs/form/README.md This JSON snippet provides an example of the `action.payload.value` structure that is passed to reducers when a form changes. It represents the raw form values as an object, with keys corresponding to input names and nested objects for form groups. This structure is crucial for manually updating Redux state when not using the default reducer. ```JSON { "address1": "129 Spadina Ave", "address2": "Toronto, Ontario M4Y 1F7", "otherGroup": { "foo": "bar", "biz": 1 } } ``` -------------------------------- ### Dispatching Actions to NgRedux Store in Angular Source: https://github.com/angular-redux/platform/blob/master/docs/store/articles/intro-tutorial.md This snippet demonstrates how to dispatch INCREMENT and DECREMENT actions to the Redux store using NgRedux.dispatch() when buttons are clicked in an Angular component. It shows the necessary imports and constructor injection for NgRedux and CounterActions. ```typescript // Imports as before. import { NgRedux } from '@angular-redux/store'; // <- New import { CounterActions } from './app.actions'; // <- New import { IAppState } from '../store'; // <- New @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app works!'; count: number; constructor( // <- New private ngRedux: NgRedux, // <- New private actions: CounterActions ) {} // <- New increment() { this.ngRedux.dispatch(this.actions.increment()); // <- New } decrement() { this.ngRedux.dispatch(this.actions.decrement()); // <- New } } ``` -------------------------------- ### Example Form Data Payload for Custom Reducer Source: https://github.com/angular-redux/platform/blob/master/packages/form/README.md Shows the expected JSON structure of the `action.payload.value` when handling `FORM_CHANGED` actions manually in a custom reducer. This object contains raw form values, including nested groups. ```json { "address1": "129 Spadina Ave", "address2": "Toronto, Ontario M4Y 1F7", "otherGroup": { "foo": "bar", "biz": 1 } } ``` -------------------------------- ### Configuring Redux Store in Angular AppModule Source: https://github.com/angular-redux/platform/blob/master/packages/store/articles/intro-tutorial.md This Angular `AppModule` snippet demonstrates how to integrate the Redux store into an Angular application. It imports the `rootReducer` and `INITIAL_STATE`, then uses `NgRedux.configureStore` in the constructor to set up the Redux store, making it available throughout the Angular application. ```typescript import { rootReducer, IAppState, INITIAL_STATE } from '../store'; import { CounterActions } from './app/app.actions'; @NgModule({ declarations: [AppComponent], imports: [BrowserModule, FormsModule, HttpModule, NgReduxModule], providers: [CounterActions], bootstrap: [AppComponent], }) export class AppModule { constructor(ngRedux: NgRedux) { // Tell @angular-redux/store about our rootReducer and our initial state. // It will use this to create a redux store for us and wire up all the // events. ngRedux.configureStore(rootReducer, INITIAL_STATE); } } ``` -------------------------------- ### Implementing Redux Root Reducer and Application State Interface in TypeScript Source: https://github.com/angular-redux/platform/blob/master/docs/store/articles/intro-tutorial.md Defines the `IAppState` interface for the application's state, the `INITIAL_STATE`, and the `rootReducer` function. The reducer takes the current state and an action, returning a new state based on `INCREMENT` or `DECREMENT` actions. ```typescript import { Action } from 'redux'; import { CounterActions } from './app/app.actions'; export interface IAppState { count: number; } export const INITIAL_STATE: IAppState = { count: 0, }; export function rootReducer(lastState: IAppState, action: Action): IAppState { switch (action.type) { case CounterActions.INCREMENT: return { count: lastState.count + 1 }; case CounterActions.DECREMENT: return { count: lastState.count - 1 }; } // We don't care about any other actions right now. return lastState; } ``` -------------------------------- ### Unit Testing Angular Redux Store Selections with MockNgRedux Source: https://github.com/angular-redux/platform/blob/master/packages/store/articles/intro-tutorial.md This snippet demonstrates how to unit test components that use `@select` or `ngRedux.select` by integrating `NgReduxTestingModule` into Angular's `TestBed`. It shows how to use `MockNgRedux.getSelectorStub` to create a controllable Observable stub for selected store properties, allowing you to drive test values and assert component behavior. ```TypeScript import { NgReduxTestingModule, MockNgRedux } from '@angular-redux/store/testing'; import { Subject } from 'rxjs/Subject'; import 'rxjs/add/operator/toArray'; import { MyComponent } from './my-component'; import { IAppState } from '../store'; import { CounterActions } from './app.actions'; describe('MyComponent', () => { beforeEach(() => { // Configure your testBed to use NgReduxTestingModule; this test the DI // in the test environment to use mock versions of NgRedux and DevToolsExtension. TestBed.configureTestingModule({ declarations: [MyComponent],      imports: [NgReduxTestingModule], providers: [CounterActions]    }).compileComponents(); // Reset the mock to start from a clean slate in each unit test. MockNgRedux.reset(); }); it('Selects the current count value from Redux', done => { // Create an instance of MyComponent using Angular's normal unit test features. const fixture = TestBed.createComponent(MyComponent); const componentUnderTest = fixture.debugElement.componentInstance; // Get a stub we can use to drive the `@select('count')` observable used by // MyComponent (above). This stub will be supplied to any relevant `.select` // or `@select` calls used by the component under test by MockNgRedux. const countStub: Subject = MockNgRedux.getSelectorStub('count'); // Determine a sequence of values we'd like to test the Redux store with. const expectedValues = [ 1, 2, 3, 4, 3, 4, 3, 2, 1]; // Drive those values through our stub. expectedValues.forEach(value => countStub.next(value)); // toArray only deals with completed streams countStub.complete(); // Make sure MyComponent's selected count$ variable receives these values. componentUnderTest.count$ .toArray() .subscribe( actualValues => expect(actualValues).toEqual(expectedValues), null, done); }); }) ``` -------------------------------- ### Dispatching Actions to Redux Store in Angular Source: https://github.com/angular-redux/platform/blob/master/packages/store/articles/intro-tutorial.md This snippet demonstrates how to dispatch INCREMENT and DECREMENT actions to the Redux store from an Angular component. It shows the necessary imports for NgRedux, CounterActions, and IAppState, and how to use ngRedux.dispatch() within component methods to trigger state changes. ```typescript // Imports as before. import { NgRedux } from '@angular-redux/store'; // <- New import { CounterActions } from './app.actions'; // <- New import { IAppState } from '../store'; // <- New @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app works!'; count: number; constructor( // <- New private ngRedux: NgRedux, // <- New private actions: CounterActions ) {} // <- New increment() { this.ngRedux.dispatch(this.actions.increment()); // <- New } decrement() { this.ngRedux.dispatch(this.actions.decrement()); // <- New } } ``` -------------------------------- ### Redux Reducer Pseudocode for State Calculation Source: https://github.com/angular-redux/platform/blob/master/packages/store/articles/intro-tutorial.md This pseudocode illustrates the core concept of a Redux reducer. It shows how a stream of actions is reduced over time to compute the next state of the application, specifically handling 'INCREMENT' and 'DECREMENT' actions for a count variable. ```js const nextValueOfCount = streamOfActions.reduce( (currentValueOfCount, action) => { switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; } return state; }, { count: 0 }, ); ``` -------------------------------- ### Redux State Update and UI Rendering Pseudocode Source: https://github.com/angular-redux/platform/blob/master/packages/store/articles/intro-tutorial.md This pseudocode provides a simplified view of the Redux cycle, showing how the `rootReducer` computes `nextState` from `lastState` and `mostRecentAction`. It then indicates that the UI re-renders based on this newly computed state, illustrating the unidirectional data flow. ```typescript const nextState = rootReducer(lastState, mostRecentAction); UI.render(nextState); ``` -------------------------------- ### Configure Router Reducer with Redux Store Source: https://github.com/angular-redux/platform/blob/master/docs/router/README.md This TypeScript snippet demonstrates how to integrate the routerReducer from @angular-redux/router into your Redux store's root reducer using combineReducers. It ensures that router state is managed within the Redux store. ```TypeScript import { combineReducers } from 'redux'; import { routerReducer } from '@angular-redux/router'; export default combineReducers({ // your reducers.. router: routerReducer, }); ``` -------------------------------- ### Accessing Properties: Mutable Objects vs. Immutable.Map Source: https://github.com/angular-redux/platform/blob/master/docs/store/articles/cookbooks.md This snippet illustrates the difference in property access syntax between a standard JavaScript object and an Immutable.Map. While mutable objects allow direct property dereferencing, Immutable.Map requires using the `get` method for safe, immutable access. ```TypeScript const mutableFoo = { foo: 1, }; const foo: number = mutableFoo.foo; ``` ```TypeScript const immutableFoo: Map = Immutable.fromJS({ foo: 1; }); const foo: number = immutableFoo.get('foo'); ``` -------------------------------- ### Conceptual Redux State Reduction with Array.prototype.reduce Source: https://github.com/angular-redux/platform/blob/master/packages/store/articles/intro-tutorial.md This pseudocode conceptually models the entire application's state evolution as a `reduce` operation over a sequence of actions. It highlights how the `rootReducer` continuously processes actions to derive the `finalAppState` from an `INITIAL_STATE`. ```typescript const finalAppState: IAppState = actionsOverTime.reduce( rootReducer, INITIAL_STATE, ); ``` -------------------------------- ### Create simple counter UI HTML Source: https://github.com/angular-redux/platform/blob/master/packages/store/articles/intro-tutorial.md Adds basic HTML structure for a counter display with increment and decrement buttons to `src/app/app.component.html`. It uses Angular's interpolation `{{ count }}` to display the counter value and event binding `(click)` to trigger `increment()` and `decrement()` methods. ```html
Count: {{ count }}
```