Get started with Angular Resolvers fast!
Join the DZone community and get the full member experience.Join For Free
What Is a Resolver?
To ensure, certain data is loaded from an API response before the route is actually activated, we use Route Resolvers.
In other words, to prefetch the data for a particular route before the component is loaded.
Why Use a Resolver?
Assume, there is a case when, in an Angular application, in a component, some elements are displayed spontaneously, but other components are loaded after Observable is subscribed successfully which might take some time to render on UI. Here, Resolvers come to the rescue. They allow applications to retrieve data first from an API response before the component gets loaded, allowing for route navigation.
Let’s, start implementing Resolvers.
You may also like: Angular Observables and Promises – How to Use Them.
Creating a Resolver Service
- Importing Resolve interface from
@angular/router, which provides a resolve method that ensures anything's data that is returned is resolved.
Resolve()has two parameters — route which is
ActivatedRouteSnapshotand state which is
Resolve()method resolves an observable:
Adding a Resolver in Route
We are adding the resolver, employee.resolve.ts, in our routes, and the resolve method, which was added in our resolver will return the resolved data into the key named
Accessing Resolved Data in our
Resolved data can be accessed using the key defined in our routes using the ActivatedRoute’s snapshot object.
Displaying the Resolved Data in HTML
And that's how the resolver works — make your data available before the router starts working and components get loaded!
Opinions expressed by DZone contributors are their own.