Resolvers: Angular’s one-click data delivery
I’ve once read somewhere that you should always keep your Components as small as possible. It’s then easier to understand and forces you to put reusable logic in Services. But when you need to get data from an API, then you may need to map the data to fit the format you want. You’ll need to take care of all this in your Component once it’s initiated… right?
Wrong.
There’s a way to fetch everything you need before the route actually changes to initialize your Component. To do that, you’ll need a Resolver.
Resolvers in a nutshell
The Angular Router uses Guards to allow you to manage a route change. For instance, you might want to prevent navigation to (or from) a route. To do that, you will add a Guard on that route.
Resolvers are a type of Guard. It returns an Observable or a Promise and will allow the route change to proceed only upon completion of that Observable (or Promise).
To associate a Resolver with a route, you’ll need to specify a resolve key in the corresponding route.
And to access the data, your component can get it from the ActivatedRoute snapshot. You hit the ground running!
It’s as simple as that!
Link clicking feedback
There is a downside in using Resolvers that you will want to address. When navigating to a route that uses a Resolver, you’ll notice a delay between the moment you click and the moment the route actually changes. Users browsing your Angular application might not understand what’s going on and think that either your app is unresponsive or is just plainly slow.
Because your router is waiting for the Resolver to complete, it could take from milliseconds to a couple of seconds before the route actually changes (depending on the time it takes for the API to submit its response). But don’t worry, there’s a solution.
In your root Component, you can subscribe to Router events. There are many Router events, but the ones that we want to listen to are NavigationStart and NavigationEnd. These will tell us when a user has clicked a link and when the Resolver is finally done with its Observable.
In the example above, our AppComponent has a boolean property called isLoadingRoute
that is set to true
when a user clicks on a link and goes back to false
when the navigation has completed. You can then easily use that property to show some kind of loading state in your application. That way, your user will get immediate feedback when navigating your Resolver equipped routes!
Share your uses of Resolvers!
Have you used Resolvers in your projects in useful ways? Help your fellow developers by sharing snippets of them in the comments below!
Keep coding!