Gourav Pokharkar
Gourav Pokharkar

Reputation: 1648

Why to use Route Resolver if I can control DOM content using structural directives?

I am learning the use of Angular Route Resolvers, and from some sources on web, I get idea that those are used to perform actions after the navigation event and before our component is loaded.

But, if I can control the loading of DOM using structural directives like *ngIf and perform required actions in ngOnInit() before loading of DOM, then what is the use case of resolvers.

Are they efficient and performance optimizers? Is there specific case where I have no option other than using resolvers?

(I am referring to https://stackblitz.com/edit/angular-route-resolvers as an example).

Upvotes: 1

Views: 263

Answers (2)

Gokulnath
Gokulnath

Reputation: 1256

I find the resolver useful in these 2 cases:

  1. When we enable page animations, like sliding pages to the left/right in the router outlet. The animation is smoother as the component gets loaded only after the data is resolved.
  2. When data needs to be shared across child route components (it can be achieved just using services though).

For everything else I use *ngIf

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 692171

Resolvers can be useful for many reasons:

  • the page content and the URL doesn't change until the data is loaded. So it the loading fails, the user isn't in front of a blank page, and can click the link again to retry.
  • it makes the template easier to write, since you don't have to deal with data not being loaded yet, or being partially loaded
  • it makes the code of the component simpler, since the component just needs to display data provided by the resolver, rather than loading it by itself (and reloading if the parameters change).
  • if used consistently, resolvers allow using router events to display some generic loading indicator, whereas if each component loads its own data, you can centralize this code in a single place
  • the resolver can be shared between several routes that need the same data

Their downsides is that

  • it's yet another service to write, which dilutes the code of a component in one or several more additional places
  • it can give a feeling of slowness, because nothing changes on the page until the data is loaded

Upvotes: 2

Related Questions