【问题标题】:IONIC and NGRX set initial state from indexed dbIONIC 和 NGRX 从索引数据库设置初始状态
【发布时间】:2021-06-26 23:30:45
【问题描述】:

我正在使用 angular 的 Ionic 应用程序工作,我希望我的状态保持不变,所以我添加了插件 @ionic/storage-angular 来保存当前状态,当我重新启动应用程序时,我想在 ngrx 中设置之前保存的状态.

所以我创建了我的存储服务:

@Injectable({
    providedIn: 'root'
})
export class StorageService {
    state: AppState;
    constructor(private storage: Storage, public store: Store<AppState>) {
      this.createDBStorage();
      this.loadStorage();
    }

    async createDBStorage() {
      await this.storage.create();
    }

    async loadStorage() {
      const dbState = await this.storage.get('dt-config');
      if (dbState) {
        this.state = dbState;
      } else {
        this.state = null;
      }
    }


    getState() {
      return this.state || null;
    }

    saveState(newState: AppState) {
      this.storage.set('dt-config', newState);
      this.state = newState;
    }
}

我研究了如何从我的索引数据库中设置初始状态,我发现了这个 ---> How to set initialState in @ngrx/core with a promise from indexedDB 但答案是三年前的。

根据那个答案,在 app.module.ts 中有类似这样的设置初始状态

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

@NgModule({
  imports: [
    ...
    StoreModule.forRoot(reducers, {initialState: getInitialState}),
    ...
  ], bootstrap: [AppComponent],
})
export class AppModule {}

这正是我需要的问题是如何调用我的服务,或者是否有其他方法可以访问保存在索引数据库中的项目?

【问题讨论】:

    标签: angular ionic-framework local-storage ngrx ionic-native


    【解决方案1】:

    您可以使用初始值来初始化您的状态,而不是这样做。初始化应用程序后,您可以在该操作上触发 LoadAppState action &,您可以使用 Effects & reducer 来设置您的商店。 喜欢:

    ## Dispatch action on app initialization
    this.store.dispatch(LoadAppState());
    
    ###### Reducer ######
    export const reducer = createReducer(initialState,
      on(LoadAppStateSuccess, (state, action) => ([...state, action.payload])),
    )
    
    ###### Effects ######
    loadAppState$ = createEffect(() => this.actions$.pipe(
        ofType(LoadAppState),
        switchMap(() => StorageService.dB.loadInitialState('app-state')
          .pipe(
            map(appState => LoadAppStateSuccess({ payload: appState })),
            catchError(() => EMPTY)
          ))
        )
      );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 2020-11-02
      • 1970-01-01
      相关资源
      最近更新 更多