Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Resolve before CanActivate

Tags:

angular

I have an Authentication service that implements the Resolve interface to return an observable that is resolved once a user's authentication state is retrieved from the server.

This same authentication service implements the CanActivate interface to block users from accessing a component if they are not logged in.

Currently, the canActivate function is triggered before the resolve function is resolved, meaning it checks the user's login state before the login state has been retrieved from the server.

My question is, how can I prevent the canActivate function being called until resolve is resolved, or otherwise is there another way I can achieve what I want?

Thanks Max.

like image 887
Max Mumford Avatar asked Aug 28 '16 10:08

Max Mumford


2 Answers

CanActivate always runs before resolve by design..

..because the resolver should only run after the CanActivate guards have done their job (authentication, cleanup, ..). When you follow this pattern (see below), there is usually little reason to reverse or change this order.


1. CanActivate (authentication):

  • Authenticate/verify user.
  • Get tokens needed to query/get data from a server or API.
  • Use either a Promise or Observable to make sure the resolvers wait for the CanActivate guards to complete.

2. Resolve (get data):

  • When all guards have passed, then it's time for the resolvers to run.
  • Get data when you're sure the user is authenticated.
  • Get data from the server using the tokens, etc.
  • Use either a Promise or Observable to make sure the components are loaded when the resolve data is available.

3. constructor/OnInit (use data):

  • Get the data from the resolver (with, for example, ActivatedRoute.snapshot.data).
  • Render the data in your template or send it to a service.

If, somehow, you really need to wait for the resolvers to complete, just move your code from a guard to a resolver.

You can read more about this in this thread on GitHub.

like image 134
Jeffrey Roosendaal Avatar answered Sep 23 '22 09:09

Jeffrey Roosendaal


canActivate() can return a boolean, Promise<boolean> or Observable<boolean>.

If you return Promise or Observable, the component can't be navigated to until they are resolved to true.

like image 42
j2L4e Avatar answered Sep 25 '22 09:09

j2L4e