The use case: I want to redirect logged in users to /dashboard, and non-logged in users to /landing.
First take:
{
path: '**',
redirectTo: '/dashboard',
canActivate: [AuthGuard],
},
{
path: '**',
redirectTo: '/landing'
}
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService, private router: Router) {}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean|UrlTree> | Promise<boolean|UrlTree> | boolean | UrlTree {
return this.auth.isAuthenticated$
}
}
All users are redirected to the dashboard page.
Second try:
{
path: '**',
redirectTo: '/home/loggedin',
canActivate: [AuthGuard],
data: { authGuard: { redirect: '/home/loggedout' } }
},
{
path: '**',
redirectTo: '/home/loggedin'
}
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService, private router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean|UrlTree> | Promise<boolean|UrlTree> | boolean | UrlTree {
return this.auth.isAuthenticated$.pipe(
map(loggedIn => {
console.log(`A=${loggedIn} ${JSON.stringify(next.data.authGuard.redirect)}`)
if (!loggedIn && next.data.authGuard.redirect) {
return this.router.parseUrl(next.data.authGuard.redirect);
} else {
return false;
}
})
);
}
}
Seems like the AuthGuard is not even invoked. Possibly if I use a component instead of a redirect?
{
path: '**',
component: RedirectingComponent,
canActivate: [AuthGuard],
data: { authGuard: { redirect: '/home/loggedout' }, redirectComponent: { redirect: '/home/loggedin' } }
}
Now this seems to work, but it also is an awful hack.
How can AuthGuards be made to work with redirects?