Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to understand difference between canActivate and Resolver

Tags:

angular

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?

like image 668
Karthikeyan Mohan Avatar asked Oct 19 '17 20:10

Karthikeyan Mohan


People also ask

What is the difference between CanLoad and CanActivate?

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.

Can you activate vs resolve?

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.

What is the difference between CanActivate and CanDeactivate?

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.

What is CanActivate?

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.


2 Answers

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.

like image 100
DeborahK Avatar answered Sep 26 '22 19:09

DeborahK


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.

like image 35
Mohamed Gara Avatar answered Sep 25 '22 19:09

Mohamed Gara