Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 9 Router - CanActivate not working with redirects

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?

like image 618
Ákos Vandra-Meyer Avatar asked Sep 16 '25 14:09

Ákos Vandra-Meyer


1 Answers

You can achieve this using children: [] instead of setting a component (like so)

{ 
  path: '', 
  canActivate: [AuthGuard], 
  children: [] 
}
like image 197
minlare Avatar answered Sep 18 '25 11:09

minlare