如何为Angular Ngrx存储制作“还原剂增强剂”以进行撤消/重做

时间:2019-04-26 14:23:05

标签: angular redux ngrx

我想为特定的商店切片添加reducer增强器或meta reducer。我实现了一个带有reducer并启用撤消/重做功能的功能。当前看起来像这样:

export const adminReducers: ActionReducerMap<AdminFeatureState> = {
    admin: admin.reducer,
    dynamicForm: undoable(dynamicForm.reducer, DynamicFormActionTypes.UNDO, DynamicFormActionTypes.REDO, [
        DynamicFormActionTypes.SELECTED_DYNAMIC_CONTROLS_CHANGED,
        DynamicFormActionTypes.CHANGE_GROUP,
        DynamicFormActionTypes.RESET,
        DynamicFormActionTypes.ADD_PAGE,
        DynamicFormActionTypes.REMOVE_PAGE,
        DynamicFormActionTypes.REORDER_GROUPS,
        DynamicFormActionTypes.SAVE_EDIT_CONTROL
    ])
};

export function undoable<T>(reducer: ActionReducer<any>, undoActionType: string, redoActionType: string, recordedActions: string[]): ActionReducer<any> {
    // Call the reducer with empty action to populate the initial state
    const initialState: UndoableState<T> = {
        past: [],
        present: reducer(undefined, { type: 'INIT' }),
        future: []
    };

    // Return a reducer that handles undo and redo
    return function (state = initialState, action) {
    ...
    };
}

一切正常,除了我为生产而构建时,出现以下错误:

Error during template compile of 'AdminModule'
  Function calls are not supported in decorators but 'undoable' was called in 'adminReducers'
    'adminReducers' calls 'undoable' at src\app\core\containers\admin\admin-feature.reducers.ts(11,29).

我见过的可以增强现有的reducer的另一种方法是使用meta-reducer,但是每个reducer函数都会调用它们,而在这种情况下,不仅是诸如'dynamicForm'之类的特定函数。

1 个答案:

答案 0 :(得分:0)

在对文档进行一些挖掘之后,我在这里找到了解决方案:

https://github.com/ngrx/platform/blob/master/docs/store/api.md#feature-module-reducers-and-aot

您可以像这样简单地将'adminReducers'包装在CombineReducers中:

const adminReducers: ActionReducerMap<AdminFeatureState> = {
    admin: admin.reducer,
    dynamicForm: undoable(dynamicForm.reducer, DynamicFormActionTypes.UNDO, DynamicFormActionTypes.REDO, [
        DynamicFormActionTypes.SELECTED_DYNAMIC_CONTROLS_CHANGED,
        DynamicFormActionTypes.CHANGE_GROUP,
        DynamicFormActionTypes.RESET,
        DynamicFormActionTypes.ADD_PAGE,
        DynamicFormActionTypes.REMOVE_PAGE,
        DynamicFormActionTypes.REORDER_GROUPS,
        DynamicFormActionTypes.SAVE_EDIT_CONTROL
    ])
};

const adminMetaReducer = combineReducers(adminReducers);

export function enhancedAdminReducers(state, action) {
    return adminMetaReducer(state, action);
}

然后将其导入您的模块

StoreModule.forFeature(ADMIN_FEATURE, enhancedAdminReducers),