Angular Route Resolver?
This Article helps you to Understand, The Angular Route Resolver
A Resolver is a class that implements the Resolve interface of Angular Router. In fact, Resolver is a service that has to be [provided] in the root module. Basically, a Resolver acts like middle-ware, which can be executed before a component is loaded.
Why Choose Angular Resolvers?
Angular Resolvers let the application fetch remote data from the server before the activatedRoute of the next component is activated. We don’t require a spinner until the data is fetched because we won’t be able to navigate to the next component unless the server data is retrieved. so resolver:-
- Show error detail in case of any error.
- We have to fetch data before route is rendered or displayed
- We need a way to run some code before a route is rendered- a resolver.
How Resolver Different from CanActivate and CanDeactivate
Resolver, will not decide whether this route should be rendered or not or the component should be loaded or not
The resolver will always render the component in the end, but it will do some pre-loading - it will fetch some that data, the component will need later on.
Implement Resolver method
The ServerResolver Service class will automatically subscribe to the getServer observable and provide the router with the fetched data. Only resolved data could be returned from the method.
Once we are done with the above steps, we need to configure our routes to specify the data needed to be prefetched for each component. For that, modify the routes in the app-routing.module.ts file.
Within the above routes, we provide a key “resolve” containing an object to be used for extracting the data
As you can see above, the "resolve" key is associated with an object that has "server" as a key and "ServerResolver" as its value. An object with the property named server receives the data.
Before the component is loaded, the "ServerResolver() function is called, and the returned Observable is resolved.
Access the Resolved Data
For accessing the resolved data, we will use the data property of ActivatedRoute service. In the server.component.ts file, use the following code to access the data: