0.0.1 • Published 9 years ago
ngrx-state-switcher v0.0.1
ngrx-state-switcher
State switcher meta reducer for @ngrx/store (Undo-Redo functionality).
Dependencies
ngrx-state-switcher depends on @ngrx/store and Angular 2.
Usage
npm install ngrx-state-switcher --save- Import
composeandcombineReducersfrom@ngrx/storeand@ngrx/core/compose - Import
StateSwitcherclass fromngrx-state-switcher; - Create instance of
StateSwitcherclass - Invoke
getStateReducermethod ofStateSwitcherand get result (as function, let it bestateSwitchReducer). - Add
combineReducersafter stateSwitchReducer and invoke composed function with application reducers as an argument toprovideStore.
import {bootstrap} from '@angular/platform-browser-dynamic';
import {TodoApp} from './todo-app';
import {provideStore, combineReducers} from "@ngrx/store";
import {compose} from "@ngrx/core/compose";
import { StateSwitcher } from 'ngrx-state-switcher';
import {todos, visibilityFilter} from './reducers';
export function main() {
const stateSwitcher = new StateSwitcher();
const stateSwitchReducer: Function = stateSwitcher.getStateReducer();
return bootstrap(TodoApp, [
//taking all logging defaults
//todos and visibilityFilter are just sample reducers
provideStore(
compose(
stateSwitchReducer,
combineReducers
)({todos, visibilityFilter})
),
])
.catch(err => console.error(err));
}
document.addEventListener('DOMContentLoaded', main);API
StateSwitcher(actionsUnderPolicy: StateSwitchPolicy[]);
Arguments
actionsUnderPolicy(array ofStateSwitchPolicy): names of actions that will be excluded fromStateSwitcherflow.
export enum Policy {
ALWAYS,
FIRST_ONLY,
EXCEPT_FIRST
}
export interface StateSwitchPolicy {
actionName: string;
policy: Policy;
}Apart from that you can use preventDefaultInit method of StateSwitcher class to exclude default ngrx actions from StateSwitcher flow.
Example
import { compose } from '@ngrx/core/compose';
import { combineReducers } from '@ngrx/store';
import todosReducer, * as fromTodos from './todos.reducer';
import visibilityFilter from './visibiltyFilter.reducer';
import { TodoFilter } from '../models/filter.model';
import { TodoActions } from '../actions/todo.actions';
import { StateSwitcher, Policy } from './state-switcher';
export interface AppState {
todos: fromTodos.TodosState;
filter: TodoFilter;
}
const stateSwitcher = new StateSwitcher([
{actionName: TodoActions.GET_TODOS, policy: Policy.ALWAYS},
{actionName: TodoActions.ADD_TODO, policy: Policy.ALWAYS}
]).preventDefaultInit();
const stateSwitchReducer: Function = stateSwitcher.getStateReducer();
export default compose(stateSwitchReducer, storeLogger(), combineReducers)({
todos: todosReducer,
filter: visibilityFilter
});
export const getTodosState = (state: AppState) => state.todos;
export const getFilterState = (state: AppState) => state.filter;You can see here working example.
0.0.1
9 years ago