Resolver: runs before the user is redirected to a new page.
Whenever you need to get data before initializing a component, the correct way to do this is to use a recognizer. Resolver acts synchronously, i.e. The resolver will wait for the asynchronous call to complete, and only after processing the asynchronous call will it be redirected to the corresponding URL. Thus, component initialization will wait for the callback to complete. Thus, if you want to do something (calling a service), even before the component is initialized, you are in the right place.
Sample scenario: I was working on a project in which the user would pass the file name for upload to the URL. Based on the name passed, we make an asynchronous call to ngOnInit and get the file. But the problem is that if the user passes the wrong name in the URL, our service will try to get a file that does not exist on the server. We have 2 options in this scenario:
Option 1: get a list of valid file names in ngOnInit, and then call the actual service to retrieve the file (if the file name is valid). Both of these calls must be synchronous .
Option 2: Retrieve a list of valid file names in the resolver, verify the correct file name in the URL, and retrieve the file data.
Option 2 is the best choice, as the recognizer handles the synchronization of calls.
Important :: Use a resolver if you want to receive data before the user is redirected to the URL. Resolver may include service calls that provide us with the data needed to load the next page.
source share