如何使 ngrx 效果等待异步函数

Mat*_*att 6 redux ngrx ngrx-effects

我用来node-keytar在 Electron 应用程序中存储令牌。它使用承诺,因此我需要等待承诺解决才能获取令牌。

我尝试创建的效果将调用身份验证服务来获取令牌,然后使用 Angularhttp调用将该令牌发送到后端 API。这里的问题是调用 Effect 中的服务函数。由于服务功能需要await响应,keytar整个功能必须是async,但据我所知,没有办法使效果本身与关键字异步async

我应该在这里使用不同的架构吗?我尝试过使用.then()并从内部返回成功操作,但这会引发类型错误。

效果(目前有错误Type Observable<{}> is not assignable to type Observable<Action>):

  setAccount$: Observable<Action> = this.actions$.pipe(
    ofType<SetCurrentAccountPending>(AccountActions.ActionTypes.SetCurrentAccountPending),
    switchMap(action => {
      return this.accountService.setCurrentAccount(action.payload).pipe(
        map(
            () => new AccountActions.SetCurrentAccountSuccess(action.payload)
          ),
          catchError(() => {
            return of(new AccountActions.SetCurrentAccountFailure());
          })
        );
    })
  );
Run Code Online (Sandbox Code Playgroud)

服务功能:

async setCurrentAccount(id: string) {
    const password = await AccountHandler.getPasswordFromManager(id);
    const body = {password: password};
    return this.httpClient.post(environment.localApi + '/accounts/' + id, body);
}
Run Code Online (Sandbox Code Playgroud)

Fli*_*ats 8

这样的事情有帮助吗?

  setAccount$: Observable<Action> = this.actions$.pipe(
    ofType<SetCurrentAccountPending>(AccountActions.ActionTypes.SetCurrentAccountPending),
    switchMap(action => this.accountService.setCurrentAccount(action.payload)),
    map(data => new AccountActions.SetCurrentAccountSuccess(data)),
    catchError(error => of(new AccountActions.SetCurrentAccountFailure()))
  );
Run Code Online (Sandbox Code Playgroud)