【问题标题】:Convert Promise to Observable with React-Redux and TypeScript使用 React-Redux 和 TypeScript 将 Promise 转换为 Observable
【发布时间】:2025-12-21 03:00:06
【问题描述】:

我知道可用的解决方案很少,但我似乎无法完全理解这个概念。我认为如果我能找到解决我的问题的方法会更好。

我正在使用一个返回 Promise 的库,但我想将此响应(无论成功还是失败)存储到 Redux 中。

interface IResponseType {
  accessToken: string;
}

const authLogin = (
  username: string,
  password: string
): Promise<IResponseType> => {
  return new Promise(resolve => {
    return resolve({ accessToken: "something" });
  });
};

export const loginEpic: IEpic = (
  action$: ActionsObservable<ITestLoadAction>,
  store: StateObservable<IStore>
): Observable<IAction> =>
  action$.ofType(TEST.REQUEST).pipe(
    from(authLogin("username", "password")).pipe(
      map(
        (response: IResponseType): IAction => testLoadSuccessAction(response)
      ),
      catchError(() =>
        ActionsObservable.of(testLoadFailedAction("Test Loading failed."))
      )
    )
  );

IAction

interface IAction {
    type: any;
    [key: string]: any;
}

IEpic

export type IEpic = Epic<IAction, IAction, IStore, EpicDependencies>;

我遇到的打字稿错误

Argument of type 'Observable<IAction | ITestLoadFailedAction>' is not assignable to parameter of type 'OperatorFunction<ITestLoadAction, IAction>'.
  Type 'Observable<IAction | ITestLoadFailedAction>' provides no match for the signature '(source: Observable<ITestLoadAction>): Observable<IAction>'.ts(2345)

我为此创建了一个沙盒。它似乎在编辑器中给出了错误,但它编译得很好。也许我在某些配置上犯了错误。但如果需要,这里是链接。 https://codesandbox.io/embed/agitated-mccarthy-sfq01

【问题讨论】:

    标签: typescript react-redux rxjs


    【解决方案1】:

    你想要做的是使用switchMap操作符函数来完成。

    action$.ofType(TEST.REQUEST).pipe(
          switchMap(() => from(authLogin("username", "password"))), 
          map(response => testLoadSuccessAction(response)),
          catchError(() => ActionsObservable.of(testLoadFailedAction("Test Loading failed."))
    )
    

    【讨论】: