NgRx能否与Promises兼容使用?Ionic 5+Ionic Storage场景问询
NgRx 适配 Promises 实现指南
NgRx 完全支持适配 Promises,你可以轻松用返回 Promise 的 Ionic Storage 替代 HttpClient,实现 ActionA->Reducer->Effect->ActionB->Reducer 这套完整的 Redux 流程。
核心逻辑
NgRx Effects 基于 RxJS Observable 构建,但 RxJS 自带的 from() 操作符可以直接把 Promise 转成 Observable,这就实现了两者的无缝衔接。
具体代码示例
以从 Ionic Storage 读取数据的流程为例:
1. 定义 Actions
import { createAction, props } from '@ngrx/store'; // 触发数据加载的 Action export const loadData = createAction('[Data] Load Data'); // 加载成功的 Action export const loadDataSuccess = createAction('[Data] Load Data Success', props<{ data: any }>()); // 加载失败的 Action export const loadDataFailure = createAction('[Data] Load Data Failure', props<{ error: any }>());
2. 编写 Effect 处理 Promise
用 from() 把 Ionic Storage 的 Promise 转换为 Observable,再处理成功/失败分支:
import { Injectable } from '@angular/core'; import { Actions, createEffect, ofType } from '@ngrx/effects'; import { of, from } from 'rxjs'; import { map, mergeMap, catchError } from 'rxjs/operators'; import { Storage } from '@ionic/storage'; import * as DataActions from './data.actions'; @Injectable() export class DataEffects { loadData$ = createEffect(() => this.actions$.pipe( ofType(DataActions.loadData), mergeMap(() => // 转换 Promise 为 Observable from(this.storage.get('target-key')).pipe( map(data => DataActions.loadDataSuccess({ data })), catchError(err => of(DataActions.loadDataFailure({ error: err }))) ) ) ) ); constructor(private actions$: Actions, private storage: Storage) {} }
3. 编写 Reducer 更新状态
import { createReducer, on } from '@ngrx/store'; import * as DataActions from './data.actions'; export interface DataState { data: any; isLoading: boolean; error: string | null; } const initialState: DataState = { data: null, isLoading: false, error: null }; export const dataReducer = createReducer( initialState, on(DataActions.loadData, state => ({ ...state, isLoading: true, error: null })), on(DataActions.loadDataSuccess, (state, { data }) => ({ ...state, isLoading: false, data })), on(DataActions.loadDataFailure, (state, { error }) => ({ ...state, isLoading: false, error })) );
关键注意点
from()是 RxJS 原生操作符,除了 Promise,还能处理数组、Iterable 等,是衔接 Promise 和 Observable 的核心工具。- Ionic 5 和 NgRx 的兼容性没问题,只要你正常配置了 NgRx 的 Store、Effects 模块,这套流程就能正常运行。
- 不管是读写还是删除 Ionic Storage 的操作,只要返回 Promise,都可以用同样的方式接入 NgRx。
内容的提问来源于stack exchange,提问作者Felix Olszewski
相关产品推荐
相关产品推荐

