I was wondering about the same thing.
It turns out that if the initial request to the site refers to a path that has one of its components protected by the solution, the solution will be executed before any component in the tree is instantiated. Including AppComponent
.
Now the problem is that AppComponent
itself is NOT a routable component and therefore cannot access permitted data. Perhaps you could insert ActivatedRoute
into the AppComponent
and access the data through the current children
route, but it seems hacky.
I usually install a solution (or CanActivate
guard) at the root of my route hierarchy to retrieve this source data. The data itself is returned by the service and wrapped inside a ReplaySubject
. This ensures that 1) the data will be shared by all subscribers; 2) the code receiving the data will be executed only once.
In other words:
- I use observable to retrieve async data once and share it with all parts of my application that needs it.
- I rely on a route system to initiate this observable as early as possible in the application life cycle.
(But I do not use a routing system to retrieve data and share it.)
Update to respond to comments:
You must enter a dummy parent route to support security, for example:
const routes: Routes = [ { path: '',
The parent route is the βroot of my route hierarchy,β and its AuthGuard
protection is AuthGuard
to ALL child routes in the application. As you can see, the parent route has an empty path, and PageShellComponent
contains only <router-outlet></router-outlet>
. The sole purpose of this route is to maintain guard (s).
I must add that this is not very idiomatic, and I'm not sure if this is the best way to go.
source share