Angular Resolvers

DZone 's Guide to

Angular Resolvers

Get started with Angular Resolvers fast!

· Web Dev Zone ·
Free Resource


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/routerwhich provides a resolve method that ensures anything's data that is returned is resolved.
  •  Resolve() has two parameters — route which is ActivatedRouteSnapshot and state which is RouterStateSnapshot as below:

Resolve() interface

Resolve() interface
  • The 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 empData.



Accessing Resolved Data in our EmployeeDetailsComponent 

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!

Happy Reading!

Further Reading

angular 6, angular 7, angular 8, angular route, angular route 2, preloaders

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}