Search code examples
angularrxjsngrxngrx-effects

How to fix order of execution in NgRx Effects?


The effect should take payload and show it in a dialog. After the dialog IS CLOSED it should post something and dispatch a new action.

The Problem is, the action is getting dispatched before i close the dialog.

 @Effect()
  bookTable$ = this.actions$.pipe(
    ofType(BookTableActionTypes.BOOK_TABLE),
    map(action => action.payload),
    exhaustMap((booking: Booking) => this.dialog.open(BookTableDialogComponent, {
      width: this.window.responsiveWidth(),
      data: booking.booking,
    }).afterClosed()
      .pipe( () =>  this.bookTableService.postBooking(booking),
        map((res: any) => new BookTableSuccess(res)),
        catchError(error => of(new BookTableFail({error: error})))
      )));
.pipe( () =>  this.bookTableService.postBooking(booking),
        map((res: any) => new BookTableSuccess(res)),
        catchError(error => of(new BookTableFail({error: error})))
      )));

The above code should only be executed after the dialog is closed.


Solution

  • It seems like you are missing an rxjs operator inside your pipe for calling your API. Try switchMap to change the observable.

    .pipe( 
       switchMap(() =>  this.bookTableService.postBooking(booking)),
       map((res: any) => new BookTableSuccess(res)),
       catchError(error => of(new BookTableFail({error: error})))
    );