I know canActivate calls before Resolver. I have a scenario that based on a token (dynamic from url) I need to route to three different pages. Which is a better approach.
Should I use canActivate and get the data from service based on the token and route. Or I should use Resolver service to get the data based on the token and route to the component?
canActivate is used to prevent unauthorized users from accessing certain routes. See docs for more info. canLoad is used to prevent the application from loading entire modules lazily if the user is not authorized to do so. See docs and example below for more info.
CanActivate is an interface and shall used for authenticate the user and allow them conditionally access the route. CanActivate executes before Resolve. Resolve interface shall used to ensure the data available for the page to load. It executes after all the routes executed.
CanActivate : Checks route navigation before the component is loaded. CanActivateChild : Checks route children navigation before the component is loaded. CanDeactivate : Checks navigation from the current route eg leaving the partially filled form. Resolve : Resolve loads/ retrieves data before the route is activated.
CanActivatelink Interface that a class can implement to be a guard deciding if a route can be activated. If all guards return true , navigation continues. If any guard returns false , navigation is cancelled.
The Resolver is really set up to be used for retrieving data. It automatically adds the data to a data[] that you can then access from the routed component to get that data:
ngOnInit(): void {
this.movie = this.route.snapshot.data['movie'];
}
canActivate
doesn't do that and is meant more for logic executed before activating a route ... such as checking whether the user is logged in.
CanActivate is a router guard that is executed to check if the router should navigate to the route and the Resolver is a data provider, that fetch data for the component before the router starts navigation. So, because you are trying to fetch data, you should use a Resolver and not a Guard.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With