Search code examples
angularangular-router

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).


Solution

  • 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