Ihor Tkachuk Ihor Tkachuk -4 years ago 145
TypeScript Question

Angular 2 redirect if user is logged in

I have routes like this:

const routes: Routes = [
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },


export class AuthGuard implements CanActivate, CanActivateChild {
constructor(private router: Router,
private authService: AuthService) { }

canActivate() {
if (this.authService.isLoggedIn()) {
return true;
return false;

When the user visits the website, he gets redirected to the login page. Same happens when the user tries to access
route without authentication. How can I redirect the user to
if he's logged in? For example, when I visit
and I'm logged in I want to be redirected to

Answer Source

In this case I would probably redirect everything to DashboardComponent using

{path: '', redirectTo: 'dashboard', pathMatch: 'full'}

and than the dashboard component can determinate if the user is logged in or not (as it has AuthGuard active), and if the user is not logged in it would redirect him to login.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download