我想在页面加载/引导时恢复@ngrx/store。
我用@ngrx/db在浏览器的IndexedDB中保存了之前的状态,我想在我的商店的INIT_ACTION中检索这些信息。
为了实现这一点,我看到现有的metaReducers如下:
export function indexedDBSyncReducer(reducer: ActionReducer<any>): ActionReducer<any> {
return function newReducer(state, action: any) {
if (action.type == 'INITIAL_STATE') {
// Read information to db and set nextState
}
const nextState = reducer(state, action);
return nextState;
};
}问题是,要从@ngrx/db检索信息,我需要有用于访问的构造器。比如this。
metaReducers是纯函数,我如何注入Database提供程序以便在我的reducer中使用它?
发布于 2018-08-03 03:27:13
可以将托管类与返回reducer函数的方法一起使用:
@Injectable()
export class AccountReducerFactory {
// here you get your db access (or any managed service) injected
constructor(private dbService: DbService) {}
createReducer() {
return (state: AccountState, action: Action) => {
if(action.type === 'INITIAL_STATE') {
const initialState = this.dbService.readInitialState()
// do something with your initial state
}
}
}
}export const ACCOUNT_REDUCER_TOKEN = new InjectionToken<ActionReducer<Map<string, Account>>>('Account state reducer')
export function getAccountReducer(accountReducerFactory: AccountReducerFactory): ActionReducer<Map<string, Account>> {
// here you create a reducer function with access to other managed services
return accountReducerFactory.createReducer()
}
@NgModule({
imports: [
StoreModule.forFeature('account', ACCOUNT_REDUCER_TOKEN)
],
providers: [
{
provide: ACCOUNT_REDUCER_TOKEN,
// here your AccountReducerFactory class will be instantiated with its deps
deps: [AccountReducerFactory],
useFactory: getAccountReducer
}
]
})
export class AccountModule {
}这回答了如何访问ngrx reducer中的服务。至于你最初的问题,你将面临另一个更难克服的挑战: indexedDb是异步的,ngrx初始化不是。我写了一篇关于那个here的简短博客文章。
https://stackoverflow.com/questions/46811113
复制相似问题