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, they are redirected to the login page. The same happens when a user tries to access a /dashboard

route without authentication. How can I redirect the user to /dashboard

if they are logged in? For example, when I visit myapp.com

and I am logged in, I want to redirect to myapp.com/dashboard

.

+3


source to share


3 answers


In this case, I would probably redirect everything to DashboardComponent

using

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



and the dashboard component can determine if the user has been logged in or not (since it is active for AuthGuard) and if the user is not logged in, it will redirect him to login.

+2


source


You want to look at the property resolve

in the interface [ Route

].

All of the following properties are available for the route:

export interface Route {
  path?: string;
  pathMatch?: string;
  matcher?: UrlMatcher;
  component?: Type<any>;
  redirectTo?: string;
  outlet?: string;
  canActivate?: any[];
  canActivateChild?: any[];
  canDeactivate?: any[];
  canLoad?: any[];
  data?: Data;
  resolve?: ResolveData;
  children?: Routes;
  loadChildren?: LoadChildren;
  runGuardsAndResolvers?: RunGuardsAndResolvers;
  _loadedConfig?: LoadedRouterConfig;
}

      

resolve

is intended to load some types of data before going to a route. The signature resolve

looks like this:

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : Observable<T>|Promise<T>|T

      

We can ignore this signature and just override it because in this case we just want to redirect to / dashboard if the user is logged in. Otherwise, display the / login route normally.



The solution is to create a class injectable

and attach it to the login route property resolve

.

@Injectable()
export class IsLoggedIn {
  constructor(
    private router: Router, 
    private authService: AuthService) {
  }

  resolve(): void {
    if (this.authService.isAuthenticated) this.router.navigate(['/dashboard'])
  }
}

      

On your / login path, add a permission property.

{
  path: 'login',
  component: LoginComponent,
  resolve: [IsLoggedIn]
}

      

Now when the logged in user tries to go to / login , he will be redirected to / dashboard without seeing the login page.

+7


source


Probably the quickest thing to do is set up LoginComponent

.

Given that it this.authService.isLoggedIn()

returns a boolean. As LoginComponent

you can quickly check the status in ngOnInit

, as shown 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 are only adding this to ngOnInit

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

      

0


source







All Articles