Reputation: 5957
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.
Upvotes: 1
Views: 3517
Reputation: 15505
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.
Upvotes: 5
Reputation: 1320
You have to add a property on your state that indicates that validation was successful. Obviously your reducer should set the said property to true whenever the validation is successful.
Once you've done that, in your component you have to store.select
and subscribe to that slice of state and route whenever it returns true
.
Upvotes: 1