Search code examples
angularngrxngrx-router-store

Route After Action Completes - NGRX and Angular


Angular 5 and NGRX 5

I am attempting to run some custom validation after a users clicks a search button, and if the validation is successful, route to a new page.

I have an isError observable that is being populated from my store:

 isError$: Observable<boolean>;

  ngOnInit() {
    this.isError$ = this.store$.select(
      ShipmentLookupStoreSelectors.selectShipmentLookupError
    );
  } 

I am calling the search action on my store as below:

  onSearch() {
   this.store$.dispatch(new ShipmentLookupStoreActions.Search());
  }

What I am confused with is how/when to actually route to the new page? What I essentially want to happen is:

run validation

if success -> route to new page

if failure -> stay on same page with updated state (isError state will be updated to true, I have this working)

I've looked into ngrx router-store but am overall confused as the best way to implement this.


Solution

  • As https://timdeschryver.dev/blog/start-using-ngrx-effects-for-this), you can do this in an effect.

    The example in the article is when you logout, but the same counts for your use case:

    @Effect({ dispatch: false })
    logOut = this.actions.pipe(
      ofType(ActionTypes.LogOut),
      tap([payload, username] => {
        this.router.navigate(['/']);
      })
    )
    

    Notice we're using dispatch: false in order to prevent an infinite loop of dispatching actions.