Prefetching means getting data before it needs to be rendered on a screen. In this Guide you will learn how to fetch data even before a routing change. By the end of this Guide, you will be able to use a resolver, implement a resolver in an Angular app, and apply a common preloader navigation.
A resolver is a middleware service that plays a role in between a route and a component. Suppose you have a form and want it to first show an empty form to the user with no data, then display a loader while it fetches the user's data, and then hide the loader and fill the form once the data has arrived.
Usually, we get the data using
ngOnInit(), which is one of the lifecycle hooks of the Angular component. It means that after the component is loaded, we hit the request for the data and toggle the loader.
We attach a loader in every route that requires data to show just after the component is loaded. A resolver is used to minimize the use of the loader. Instead of attaching the loader in every route, you can add only one loader that works for every route.
This Guide will explain each point of the resolver with an example, so you can use it as it is in your project with the complete picture in mind.
To implement the resolver, you'll need a couple of APIs for the app. Instead of creating an API here, you can use fake APIs from JSONPlaceholder. JSONPlaceholder is one of the best API sources for learning frontend concepts without bothering about APIs.
Now that the API issues have been solved, you can start on the resolver. A resolver is nothing but a middleware service, so you'll create a service.
1$ ng g s resolvers/demo-resolver --skipTests=true
src/app/resolvers folder has been created in the service. The resolver interface has a
resolve() method with two parameters: route, the instance of
ActivatedRouteSnapshot, and state, the instance of
The loader used to write all AJAX requests in
ngOnInit(), but that logic will be replaced with
ngOnInit() in the resolver.
Next, create a service with logic to get the list of posts from JSONPlaceholder. Then call the function in the resolver and configure the route for a resolve that will wait until the resolver gets resolved. After resolving the resolver, we will get the data from the route and display it in the component.