KevinTale
KevinTale

Reputation: 1878

Wait for navigation to end then dispatch an action with ngrx and rxjs

Here is the snippet :

  goToStep$ = createEffect(() =>
    this.action$.pipe(
      ofType(RouterActions.goToStep),
      tap(({ path, query: queryParams, extras }) =>
        this.router.navigate([path], { queryParams, ...extras })
      ),
      map(() => RouterActions.nextOrBack())
    )
  );

I want the RouterActions.nextOrBack() to be dispatch only after the previous navigation is done. How can I achieve this?

Thank you

Upvotes: 0

Views: 687

Answers (1)

frido
frido

Reputation: 14129

Use switchMap (you can return promises in switchMap):

this.action$.pipe(
  ofType(RouterActions.goToStep),
  switchMap(({ path, query: queryParams, extras }) =>
    this.router.navigate([path], { queryParams, ...extras })
  ),
  // everything below is executed after this.router.navigate emits
  map(() => RouterActions.nextOrBack())
)

router.navigate returns a promise that:

  • resolves to true when navigation succeeds,
  • resolves to false when navigation fails,
  • is rejected when an error happens.

Upvotes: 1

Related Questions