One way for handling retrieving and displaying data from an API is to route a user to a component, and then in that component’s ngOnInit hook call a method in a service to get the necessary data. While getting the data, perhaps the component can show a loading indicator.
There is another way to use what is known as a route resolver, which allows you to get data before navigating to the new route.
What is Route Resolver?
Router Resolver is actually a service. When jumping to a certain route, the service can get the current ActivatedRoute and get the data it carries. Here you can go to the server to get some data in advance, or do some data conversion before proceeding to the component. Instantiation and rendering. For example, when the user is about to jump to the feedback page of the application to fill in the feedback, we can check whether it is a logged-in user through a membership-resolver, if not, then jump to the login page, if yes, display the historical feedback and feedback filling form Entrance.
Why Use Route Resolvers?
Let's think about the scenario when your logic relies on the length of an array, which is manipulated when an API call is completed. For example, you may want to display in a component the items of this array which were just fetched in an unordered list.
In this situation, you might get into a problem because your data will come up after the component is ready. Items in the array do not really exist yet. Here, the Route Resolver comes in handy. It will fetch your data before the component is ready. Your conditional statements will work smoothly with the Resolver.
Implementing a Route Resolver
After we have finished with the basics explanation on why and how to use a route resolver, let’s start implementing one. In this short example, I will demonstrate only the mandatory code.
First of all, we will need a service that will fetch the user data for us. In this service, we have a function called getUsers() that returns an observable.