首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从@ngrx/db恢复@ngrx/store

从@ngrx/db恢复@ngrx/store
EN

Stack Overflow用户
提问于 2017-10-18 21:16:11
回答 1查看 1.3K关注 0票数 0

我想在页面加载/引导时恢复@ngrx/store

我用@ngrx/db在浏览器的IndexedDB中保存了之前的状态,我想在我的商店的INIT_ACTION中检索这些信息。

为了实现这一点,我看到现有的metaReducers如下:

代码语言:javascript
复制
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中使用它?

EN

回答 1

Stack Overflow用户

发布于 2018-08-03 03:27:13

可以将托管类与返回reducer函数的方法一起使用:

代码语言:javascript
复制
@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
      }
    }
  }
}

代码语言:javascript
复制
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的简短博客文章。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46811113

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档