使用React-Redux和TypeScript将Promise转换为Observable

时间:2019-10-08 18:50:18

标签: typescript react-redux rxjs

我知道几乎没有可用的解决方案,但是我似乎无法为这个概念而烦恼。我认为如果能找到解决问题的方法会更好。

我正在使用一个返回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

enter image description here

1 个答案:

答案 0 :(得分:1)

您要执行的操作是通过使用switchMap运算符函数完成的。

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