Reviewing Ngrx Data Flow
The Noob Way
export const INCREMENT:string = "INCREMENT"; export const EVENT_FROM_EFFECT:string = "EVENT_FROM_EFFECT";
import { INCREMENT } from "../../actions"; this.store.dispatch({ type: INCREMENT, payload: {text: "derp!"} });
import {ActionReducer, Action} from "@ngrx/store"; import {State, intitialState} from "../state/main-state"; import {INCREMENT, EVENT_FROM_EFFECT} from "../../actions"; export const mainReducer: ActionReducer<State> = (state = intitialState, action: Action) => { console.log('Action came in! ' + action.type); switch (action.type) { case INCREMENT: { console.log('the payload string is: ' + action.payload.innerObj.text); return { counter: state.counter + 1 } } case EVENT_FROM_EFFECT: { console.log('we cheesin in the reducer over here!'); return { counter: 4 } } } }
A More Classy Way
import {Action} from "@ngrx/store"; export const ActionTypes = { SEARCH: 'SEARCH', GET_VIDEOS: 'GET_VIDEOS' }; interface IVideosObj { something:string; others:string; } export class SearchAction implements Action { type = ActionTypes.SEARCH; constructor(public payload: string) { } } export class GetVideosAction implements Action { type = ActionTypes.GET_VIDEOS; constructor(public payload: IVideosObj) { } } export type Actions = SearchAction | GetVideosAction;
import {Store} from '@ngrx/store'; import {State} from "../../main-reducer"; constructor(private store:Store<State>) { this.store.dispatch(new actionCreator.SearchAction()); }
The New Reducer
import {ActionReducer, Action} from '@ngrx/store'; import {ActionTypes} from "../actions/main-action-creator"; export const mainStoreReducer: ActionReducer<State> = (state = intitialState, action: Action) => { switch (action.type) { case ActionTypes.AUTH_SUCCESS: { ..... } case ActionTypes.BEGIN_ANONYMOUS_AUTH: { ...... } } } }