2
votes

I am trying to implement a "workspace" feature into an Angular ngrx 4 webapp that allows the user to have multiple states of the same app which he can switch between through ui elements on the screen. How would I implement this on my reducer state?

Currently my rootReducer looks like this:

export const reducers: ActionReducerMap<State> = {
   layout: fromLayout.layoutReducer,
   properties: fromProperties.propertiesReducer,
   grid: fromGrid.gridReducer
}

Now I would like to nest these so I can change the whole state by switching workspaces.

Say I would like to switch a workspace I can not add this workspaceReducer in any of the current reducers. It would have to be a parent to the current ActionReducerMap (at least I think so).

What is the best practice to implement something like this in ngrx. T

1
can you explain more on your question. you already nested everything in this using a ActionReducerMapAravind
I am having a problem describing it. All of the shown state is dependent on what workspace is selected. Where would this workspace reducer go? That would be the parent to the currently show reducers?Jason
you want to switch the states, not the reducers. what is a reducer? it's just a reference to a switch case statement. if I understood you correctly.Daniel Netzer
Maybe... tbh I am not sure what to call what I want to do. That makes it hard to research. But yes I would like to switch the complete State of the app when a certain event is fired. How would that work?Jason
try and draw diagrmas maybe of the switch itself, between what two states you want to transition. but think of the InitialState object that you pass to the reducer to reset the state, you can create other objects similar and when the event fired just pass that Object to the reducer as an Action.Daniel Netzer

1 Answers

3
votes

You can probably use a meta-reducer:

export const SWITCH_WORKSPACE = 'SWITCH_WORKSPACE';

export function switchWorkspace( reducer ) {
  return function newReducer( state, action ) {

    if ( action.type === SWITCH_WORKSPACE ) {
      state = getWorkspaceState(action.workspace);
    }

    const nextState = reducer(state, action);

    return nextState;

  }
}

And in your app module:

StoreModule.forRoot(reducers, { 
    metaReducers: [switchWorkspace]
}),

For more info on meta-reducers, see https://netbasal.com/implementing-a-meta-reducer-in-ngrx-store-4379d7e1020a