导入服务器状态后的角度通用,@ ngrx / store / update-reducers操作擦除存储

时间:2018-06-15 12:14:15

标签: angular ngrx angular-universal ngrx-store

在成功将传输状态导入存储区后,在ssr模式下的角度通用项目中,下一个调度的操作@ngrx/store/update-reducers将擦除存储。实际上,已触发多个@ngrx/store/update-reducers操作(> 10)。

检查@ ngrx / store-devtools(chrome扩展名)错误地显示@ngrx/store/update-reducers之后的商店仍然填充了数据,但事实并非如此,我看到cmp中先前加载的数据在快速时刻后消失(当这提到的行动火了)。

它仅在ssr模式下发生,尽管经典@ngrx/store/update-reducers中的@ ngrx / store-devtools中仍存在多个ng serve

DEPS: 角度5.2.7, @ ngrx / {store,effects,store-devtools,router-store} 5.2.0, 铬66

1 个答案:

答案 0 :(得分:0)

通常,@ngrx/store/update-reducers从延迟加载的功能模块中添加缩小器。因此,我认为在您的情况下,多个功能模块是延迟加载的。

最有可能发生的情况是,在为延迟加载的模块添加减速器之前,已设置传输状态。默认情况下,ngrx会清除未分配减速器的所有状态部分(这在combineReducers函数中完成,该函数在分派的每个动作上运行)。

可能的解决方案:

1。在根模块中为功能模块分配默认的减速器

StoreModule.forRoot(initialReducerMap, { initialState: getInitialState })
export function defaultReducer(state) { return state; }

export const initialReducerMap = {
    // this will make sure `feature1` and `feature2` parts are not cleared on next action
    feature1: defaultReducer,
    feature2: defaultReducer
} as ActionReducerMap<ApplicationState>;


export function getInitialState() {
    return {
        feature1: feature1.initialState,
        feature2: feature2.initialState
    };
}

this blog post中的更多信息

2。手动为延迟加载的模块设置传输状态部分

import { ActionReducer, UPDATE } from "@ngrx/store";

let transferedState: any;
export function stateSetter(reducer: ActionReducer<any>): ActionReducer<any> {
  return function(state: any, action: any) {
    if (action.type === 'SET_ROOT_STATE') {
      transferedState = action.payload;
      return action.payload;
    }

    // on "update-reducers" set their initial transfered state
    if (action.type === UPDATE && transferedState && action.features) {
        const features: string[] = (action as any).features;
        const newState = { ...state };
        for (const feature of features) {
            newState[feature] = newState[feature] || transferedState[feature];
        }
        return reducer(newState, action);
    }

    return reducer(state, action);
  };
}

其他

请参阅this github issue