February 5, 2021
I have a route in my application that allows a user to view a blog post, I can set it up that Angular routes a user to the BlogPostComponent and in the component it requests the post from my API to render for the user.
But that doesn’t really feel right does it? Loading a page to then be presented with a loader until the content is ready, also, is this the job of the BlogPostComponent to retrieve its data?
This is where resolvers come in:
Resolvers can be thought of as “step-in” code that can be called before the Angular Router activates your component to resolve anything your component might/should have on load.
So we can make a resolver class BlogPostResolver that steps in and loads the requested blog post before the component is loaded:
Then add the resolver as a requirement for our route:
This data is then accessible in the component via importing ActivatedRoute and accessing it with the given key in the resolve property of your route, so in our case post as seen below:
We can now use the data to render the post, no loaders needed!
You can have as many resolvers for a route as you’d like, and they can be responsible for more than just data retrieval.
A Web, Tech, Football and Video Game enthusiast. Anything can be settled in smash! I’m a Software Engineer on the nerd.vision team with various front-end and back-end skills.