problem description
We know that @ angular/router provides RouteGuard for access control of routing and navigation, and provides two ways to use guard, such as CanActivate and CanActivateChild, such as
.routes = [
{
path: "advisors/:id",
component: AdvisorComponent,
canActivate: [AuthGuard], // AuthGuard
canActivateChild: [AuthGuard], //
children: [
{
path: "households/:id",
component: HouseholdComponent,
// canActivate: [AuthGuard],
},
{
path: "contacts",
component: ContactComponent,
// canActivate: [AuthGuard],
}
]
}
];
in this way, when you switch from route1 advisors/1/households/1
to route2 advisors/1/households/2
, AuthGuard is also executed to determine whether the user is logged in, otherwise the navigation fails. If canActivateChild: [AuthGuard]
is commented out, AuthGuard, will not run after switching from route1 to route2 because the canActivate of @ angular/router is designed to only be responsible for the current segment (segment), only local, not global (or add canActivate: [AuthGuard]
to each subsegment).
of course, switching from route1 to route2 must still have to run AuthGuard to determine whether the user is logged in or not.
several questions
- this kind of canActivate is only responsible for the design of the current segment (segment), which makes the code suspect of repetition. Why not design it so that when route1 switches to route2, it still executes the AuthGuard? in the parent segment canActivate? Is there any special reason for this design?
- what is the detailed internal process of Router in run guard? (admit that the problem is a little too big and broad)