【问题标题】:Why is Async Await not working with Angular @Action为什么 Async Await 不能与 Angular @Action 一起使用
【发布时间】:2020-06-13 09:03:26
【问题描述】:

这可行,但如果可能,我想在链中添加更多操作。

this.store.dispatch(new UploadPendingFiles(pendingFiles));
this.actions$.pipe(ofActionSuccessful(UploadPendingFiles)).subscribe(() => {
    alert('UploadPendingFilesComplete');
    this.store.dispatch(new CreateEmailLink(this.getPayload())).subscribe(
        () => {
            this.sent.emit('true');
        },
        (error) => {
            console.log(error);
            this.errors$.next(error.messages);
        }
    );
});

希望这种风格使用更多的 async-await,但它会在错误的时间触发。

this.store.dispatch(new UploadPendingFiles(pendingFiles));
    alert('UploadPendingFilesComplete');
// Need alert to proc here
    await this.actions$.pipe(ofActionSuccessful(UploadPendingFiles));
    // await Another @Action
    await this.store.dispatch(new CreateEmailLink(this.getPayload()));
// Alert procs here at the moment

@Action 的 sn-p

 @Action(UploadPendingFiles)
    uploadPendingFiles(ctx: StateContext<DriveStateModel>, action: UploadFiles) {
     return this.uploads.start(action.files, config).pipe(
            tap((response) => {
}
}

【问题讨论】:

    标签: angular ngxs


    【解决方案1】:

    store.dispatch() 返回一个 Observable,它在成功时完成。您可以执行以下操作:

    this.store.dispatch(new UploadPendingFiles(pendingFiles)).pipe(
      concatMap(() => this.store.dispatch(new CreateEmailLink(this.getPayload()))
    ).subscribe(() => {
      // Alert procs here at the moment
    });
    

    显然你也应该可以使用.toPromise(),但我建议你不要那样做,因为Observables 更灵活。如果你想做承诺,你可以这样做:

    async whatEverMethod(): Promise<any> {
      await this.store.dispatch(new UploadPendingFiles(pendingFiles)).toPromise();
      await this.store.dispatch(new CreateEmailLink(this.getPayload()).toPromise();
    
      //alert procs here at the moment
    }
    

    【讨论】:

    • Kruijit 感谢您的精彩解释和多种解决方案。我用了你的 defer 方法,效果很好。我想使用 toPromise(),但我不确定失去灵活性有什么区别。我尝试从 ngxs 阅读文档,但找不到任何东西。
    • 我有点惊慌失措,延迟没有触发发送电子邮件,但 .toPromise() 有效,除了我听不到错误。最后我可能不得不将它恢复到原来的样子,看起来不是最好的,但至少它可以工作。还是谢谢
    • @Gavin 我已经删除了我的 concat 解决方案,那是错误的运算符。你应该使用concatMap 来处理连续的 Observables
    • 我从来不知道ngxs dispatch 会返回 Observable。它比ngrx dispatch / effects 更有意义,样板太多。我想我总有一天会将 ngrx 迁移到 ngxs。
    • @HTN 我没有加入 react/store 的潮流,主要是因为 ngrx 样板,直到 ngxs 出现,一切都变得更加简单/整洁:)
    【解决方案2】:

    async/await 只是一种用于Promise 的语法。您不能将它与Observable 之类的其他任何东西一起使用,即action$

    等待动作的结果有点奇怪,应该使用correlationId 来完成,这会使代码更加复杂。这就是为什么我不想在这些情况下使用 Redux 的 Effect 的原因。

    【讨论】:

    • 谢谢你,但我已经有一个使用 @Action 的现有代码库,我在 Action 返回时尝试了 .toPromise() 但也失败了。在我目前的情况下使用订阅是唯一的方法吗?
    猜你喜欢
    • 2022-01-21
    • 2018-04-11
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 2023-01-17
    • 2015-06-30
    相关资源
    最近更新 更多