当使用Local storage来存储NGRX状态时,我们需要确保状态是immutable(不可变的)的。原因是我们需要在每次更新状态时创建一个新的对象,以便在存储状态时避免出现任何类型的副作用。 以下是在Angular中保存NGRX状态的示例代码:
import { Action, ActionReducer, MetaReducer } from '@ngrx/store';
export function localStorageSyncReducer(reducer: ActionReducer): ActionReducer {
return (state: any, action: Action): any => {
const nextState = reducer(state, action);
const serializedState = JSON.stringify(nextState);
localStorage.setItem('state', serializedState);
return nextState;
};
}
export function localStorageSyncReducerFactory(reducer: ActionReducer): ActionReducer {
return localStorageSyncReducer(reducer);
}
export const metaReducers: MetaReducer[] = [localStorageSyncReducerFactory];
此代码使用localStorageSyncReducer作为一个高阶reducer来处理同步操作并将状态存储在Local storage中。 在应用程序启动时,您可以通过检查Local storage中的值来还原状态,如下所示:
export function getInitialState() {
const serializedState = localStorage.getItem('state');
if (serializedState === null) {
return undefined;
} else {
return JSON.parse(serializedState);
}
}
@NgModule({
imports: [
...
StoreModule.forRoot(reducers, { initialState: getInitialState }),
...
],
...
})
export class AppModule { }
以上是使用Local storage在Angular中保存NGRX状态的完整示例。