Ihor Tkachuk Ihor Tkachuk - 1 year ago 72
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] },
];


and
AuthGuard
:

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

canActivate() {
if (this.authService.isLoggedIn()) {
return true;
}
this.router.navigate(['login']);
return false;
}
}


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

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