Angular 2 redirect if user is logged in

Viewed 11734

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.

3 Answers

Probably the quickest thing to do is to tweak your LoginComponent.

Given that this.authService.isLoggedIn() returns a boolean. In your LoginComponent you can quickly check the state in ngOnInit as below:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

import {AuthService} from '<path_to_your_auth_service>';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
  providers: []
})
export class LoginComponent implements OnInit {
  constructor(
    private _route: ActivatedRoute,
    private _router: Router,
    private _authService: AuthService
  )

  ngOnInit() {
    // get return url from route parameters or default to '/'
    this.returnUrl = this._route.snapshot.queryParams['returnUrl'] || '/';

    // CHECK THE isLoggedIn STATE HERE 
    if (this._authService.isLoggedIn()) {
      this._router.navigate([this.returnUrl]);
    }

  }

  // Rest fo the logic here like login etc

  login() { }

}

Note that you're only adding this to ngOnInit

if (this._authService.isLoggedIn()) {
  this._router.navigate([this.returnUrl]);
}
Related