首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使ngrx效果等待异步函数

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

Stack Overflow用户
提问于 2019-04-09 03:04:35
回答 1查看 5.1K关注 0票数 4

我正在使用node-keytar在电子应用程序中存储令牌。它使用Promise,因此我需要等待Promise解析才能获得令牌。

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

这里有没有我应该使用的不同的架构?我尝试使用.then()并从内部返回成功操作,但这抛出了类型错误。

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

代码语言:javascript
复制
  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());
          })
        );
    })
  );

服务功能:

代码语言:javascript
复制
async setCurrentAccount(id: string) {
    const password = await AccountHandler.getPasswordFromManager(id);
    const body = {password: password};
    return this.httpClient.post(environment.localApi + '/accounts/' + id, body);
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-09 05:25:50

像这样的东西有帮助吗?

代码语言:javascript
复制
  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()))
  );
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55580148

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档