angular - 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 {}
这正是我需要的问题是如何调用我的服务,或者是否有其他方法可以访问保存在索引数据库中的项目?
解决方案
您可以使用初始值初始化您的状态,而不是这样做。初始化应用程序后,您可以触发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)
))
)
);
推荐阅读
- xaml - 如何为 xaml 控件创建一个通用的超类?
- c++ - cpp 中定义的模板方法的 std::enable_if
- python - Python 在文件中查找特定行并在其下方追加
- java - 如何在 DynamoDB 上使用 DATE_PART(MONTH, month)?
- python - 在 Tensorflow 2.0 中记录到 tensorboard 的内部损失函数
- .htaccess - htaccess 重定向来自多个子域的链接
- mpeg-dash - 有没有办法从 dash.js 播放器中的 DASH 清单中获取媒体文件的 URL(所有表示形式)?
- c# - 可以从 C# 中的定义函数内部访问变量名称吗?
- python - folium,plugins.TimestampedGeoJson,“时间不可用”
- javascript - 如何使用纯javaScript遍历dom、交换图片、替换jQuery函数