Search code examples
angularngxs

Why is Async Await not working with Angular @Action


This works, but I would like to add more actions in a chain if possible.

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);
        }
    );
});

Would like this style with using more async-await, but it fires things at the wrong times.

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

A snippet of @Action

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

Solution

  • The store.dispatch() returns an Observable which completes on success. You can do the following:

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

    Obviously you should also be able to use .toPromise(), but I suggest you do not go that way, as Observables are way more flexible. If you want to do promises, you can do the following:

    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
    }