首页 > 解决方案 > IONIC 和 NGRX 从索引数据库设置初始状态

问题描述

我正在使用 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;
    }
}

我研究了如何从我的索引数据库中设置初始状态,我发现了这个--->如何在@ngrx/core 中设置初始状态并得到 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 {}

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

标签: angularionic-frameworklocal-storagengrxionic-native

解决方案


您可以使用初始值初始化您的状态,而不是这样做。初始化应用程序后,您可以触发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)
      ))
    )
  );

推荐阅读