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.
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):
Promise
or Observable
to make sure the resolvers wait for the CanActivate guards to complete.2. Resolve (get data):
Promise
or Observable
to make sure the components are loaded when the resolve data is available.3. constructor/OnInit (use data):
ActivatedRoute.snapshot.data
).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.
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
.
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