Understanding Resolvers in Angular.

Ophir Raj
codeburst
Published in
3 min readOct 24, 2017

--

Just like every important thing in angular, resolver is also a class. In fact, Resolver is a service which has to be [provided] in root module.

To understand the use of resolvers, Lets see how the flow happens, when someone clicks the link.

General Routing Flow.

  1. User clicks the link.
  2. Angular loads the respective component.

Routing Flow with Resolver

  1. User clicks the link.
  2. Angular executes certain code and returns a value or observable.
  3. You can collect the returned value or observable in constructor or in ngOnInit, in class of your component which is about to load.
  4. Use the collected the data for your purpose.
  5. Now you can load your component.

Steps 2,3 and 4 are done with a code called Resolver.

So basically resolver is that intermediate code, which can be executed when a link has been clicked and before a component is loaded.

Lets see how to create, where to use and how to use a resolver?

Creating a Resolver.

  1. Create a service.
  2. Import “Resolve” interface from ‘@angular/router’.
  3. Implement the interface with your class
  4. Override resolve() method.
  5. Resolve method should have two parameters. One is routesnapshot and other one is statesnapshot. Check this link for more.
  6. Resolve method should return a value or observable, if you want to use it later in your loaded component class.

In above code, I am collecting routeparams and logging it to console. You can use these routeparams here in resolver and take decisions on how to load your component or even redirecting to other path. You can do many things in resolver itself.

Finally I am returning a observable here.

Defining a Resolver in Route

Routes are defined in array of objects. Each object has keys like path, component, redirectTo, pathMatch, resolve etc. This resolve key holds another object where you will define a key and assign your resolver service as a value to it. Before doing this, you have to import your resolver service and provide in providers set of NgModule decorator.

cres is the key which i have defined and it holds AppResolver service

Using Resolver

I will use this resolver in my component which is loaded after resolving the route.

I’ am mapping my data in activated route and picking my resolver with name cres which i defined as key in route object.

Here is the output.

I navigated to ‘one ’route with ‘ophir ’as param. Then I collected that param in resolver and logged in console. Then i have sent request and then returned observable. I subscribed to observable in my class, request finished and then my component got initiated.

This is how i controlled the flow which began after router initialisation then it continued with processing the http request in resolver and then I collected data in the component. After this my component DOM got initiated.

--

--