【问题标题】:How to set initialState in @ngrx/core with a promise from indexedDB如何使用 indexedDB 的承诺在 @ngrx/core 中设置 initialState
【发布时间】:2017-12-10 07:37:36
【问题描述】:

我想使用 idb 包在 ngrx 中设置初始状态,该包使用 Promise 来获取数据,但每次尝试设置时都会出错。我读到@ngrx 是同步的,这是否意味着它不适用于承诺。 我尝试过的不同方法:

这是我的 idb 包装器方法,它可以正常加载数据

export function getInitialState(): Promise<any> {
  return StorageService.dB.loadInitialState('app-state');
}

以及我尝试设置初始状态的不同方法

方法:1

StoreModule.forRoot(reducers, {initialState: getInitialState})

方法:2

 import { INITIAL_STATE } from '@ngrx/store';
{ provide: INITIAL_STATE, useFactory: getInitialState }

方法:3

export function logger(reducer: ActionReducer<State>): ActionReducer<State> {
  return function (state: State, action: any): State {
   if(action.type === '@ngrx/store/init') {

   }
    return reducer(state, action);
  };

}

初始化状态被设置为这个

ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array(0)}

我得到了这个错误

ERROR TypeError: Cannot assign to read only property '__zone_symbol__state' of object '[object Object]'
    at resolvePromise (zone.js:810)
    at eval (zone.js:876)
    at ZoneDelegate.invokeTask (zone.js:425)
    at Object.onInvokeTask (core.js:4747)
    at ZoneDelegate.invokeTask (zone.js:424)
    at Zone.runTask (zone.js:192)
    at drainMicroTaskQueue (zone.js:602)
    at ZoneTask.invokeTask [as invoke] (zone.js:503)
    at invokeTask (zone.js:1540)
    at IDBRequest.globalZoneAwareCallback (zone.js:1566)

*******更新*******

我现在明白了,因为 dee zg 指出每个状态都可以在其效果中具有一个 init 函数,该函数将在加载时触发,我起初认为这是一个全局的一次性事件。这是我用于身份验证状态的一种

 @Effect()
  init$: Observable<Action> = defer(() => {
    return from(StorageService.readItem('app', Auth.AUTH_KEY)).pipe(
       map((data: any) => {
        return new Auth.AuthInit(data.state);
      })
    );
  });

【问题讨论】:

    标签: angular indexeddb ngrx ngrx-store


    【解决方案1】:

    效果中有一个init 动作,当效果运行时触发。在那里,您可以调度您的操作、获取数据并填充初始状态。 在此处查看Init Action 部分: https://github.com/ngrx/platform/blob/master/MIGRATION.md

    【讨论】:

    • 不知道 init 存在谢谢,但在他们的例子中他们使用 defer ex: init$: Observable = defer(() => of(new RootInit()));我怎样才能在那里调用一个承诺以使用 RootInit 作为有效负载发送。
    猜你喜欢
    • 1970-01-01
    • 2020-03-30
    • 2021-11-15
    • 2016-10-02
    • 2021-06-29
    • 2019-06-17
    • 2018-03-31
    • 2019-11-03
    • 2017-10-25
    相关资源
    最近更新 更多