I have a problem that when I logout and navigate to /
, canActivateChild guards are not executed to redirect to login.
My requirement is that none of the app is accessible without login.
Here is my root Route config:
const appRoutes: Routes = [
{
path: '',
pathMatch: 'full',
redirectTo: '/dashboard',
},
{
path: 'login',
component: LoginComponent
},
{
path: '',
runGuardsAndResolvers: 'always',
children: [
{ path: 'dashboard', component: DashboardComponent },
],
canActivateChild: [AuthGuard],
}
// { path: '**', component: PageNotFoundComponent }
];
Here is my AuthGuard (userState
) is called from canActivateChild
private userState(nextRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean|UrlTree> {
return this.auth.authState.pipe(
first(),
map(user => {
if (user != null) {
return true;
} else {
const url = this.router.parseUrl('/login');
console.log('redirect url', state.url);
url.queryParams['redirect'] = state.url;
return url;
}
}),
);
}
On login, I navigate to either /
or redirect
queryParam, if it exists.
On logout, I navigate to /
, the idea is that it will redirect to dashboard
, and, since dashboard is protected and user is null, go to /login?redirect=dashboard
.
Everything works, except the last part. When I logout, it redirects to dashboard but DOES NOT activate the canActivateChild guard, completing the redirect to dashboard with success. If I replace canActivateChild
with canActivate
, it works as desired.
More details:
- I am using Angular 7.
- Perhaps Angular 4 CanActivateChild doesn't work is a similar problem.