Karthikeyan Mohan
Karthikeyan Mohan

Reputation: 349

Trying to understand difference between canActivate and Resolver

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?

Upvotes: 14

Views: 13514

Answers (2)

Mohamed Gara
Mohamed Gara

Reputation: 2935

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.

Upvotes: 23

DeborahK
DeborahK

Reputation: 60596

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.

Upvotes: 22

Related Questions