Angular Routing Data with NGRX Effects

Image for post
Image for post

When a route changes and we load a component, we usually need to resolve some data for the component to load. Today you might use route resolvers or route guards to fetch the data and load the data. If you are using NGRX and NGRX effects you might typically dispatch a event to load this, this usually looks like this:

and its bound to our routes like this:

The more I did this over and over the more it felt oddball in a observable stream world. What if we listened to route changes in an effect and just triggered events then? That would feel nice in our stream world!

Most of us probably already have some setup for navigating with effects like suggested by NGRX so why not just listen to router events here and dispatch a event. Once we dispatch that we can then listen for that action in our effect and do this loading for us!

then in our effect, we just need to listen for the action and dispatch our LoadPizza action.

That pretty nice! But wait, we can clean that up a little with a custom RX operator:

Now our code can be as simple as:

@Effect() pizzaRouted = this.actions$.pipe(ofRoute('pizza/:id'))

One caveat to this is we can’t actually prevent the component from loading before our data is resolved. My answer to that is you shouldn’t be doing that! We want to give the user instant satisfaction so going ahead and loading the page and throwing up a spinner or something while you wait is the ideal solution. In a observable world, when the data is resolve it will already be a stream and just pick up the new changes.

This feels really nice to me and fits the observable stream model we have going on with NGRX.

Image for post
Image for post

I hope you enjoyed the post, if you liked it follow me on Twitter and Github for more JavaScript tips/opinions/projects/articles/etc!

Written by

Crafter of Software • Lover of #JavaScript #goldendoodles & #opensource

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store