Search code examples
angularangular-router-guards

Angular redirect to dashboard if user is logged in


I am using Angular v6, I have implement redirect from dashboard to login page if user is not logged in.
I'm confused between the two options:

  1. Add a login guard file to check login status and redirect to dashboard
  2. Detect route changing event, check login status here and redirect

What is the better solution for this case ?


Solution

  • Use Authentication Guard in your routing module It will make things easy for you to check whether a user is login or not

    For a better understanding of Auth Guard here are some links that might help you :

    http://jasonwatmore.com/post/2018/05/23/angular-6-jwt-authentication-example-tutorial

    How to use angular 6 Route Auth Guards for all routes Root and Child Routes?

    https://medium.com/@ryanchenkie_40935/angular-authentication-using-route-guards-bf7a4ca13ae3

    https://scotch.io/courses/routing-angular-2-applications/canactivate-and-canactivatechild

    Here is my code that I used in my project!

    In-app module file I used auth guard like this :

    const ROUTES = [
      { path: '', redirectTo: 'home', pathMatch: 'full' },
      { path: 'login', component: LoginComponent },
      { path: 'register', component: RegisterComponent },
      { path: 'home', component: HomeComponent },
      { path: 'books', component: BookComponent,canActivate:[AuthGuardService] },
      { path: 'book-details/:id', component: BookDetailComponent,canActivate:[AuthGuardService] },
      { path: 'book-create', component: BookCreateComponent,canActivate:[AuthGuardService] },
    ];
    

    And here is my auth guard service :

    import { Injectable } from '@angular/core';
    import { Router, CanActivate } from '@angular/router';
    
    
    @Injectable()
    export class AuthGuardService implements CanActivate {
    
        constructor( public router: Router) { }
    
        canActivate(): boolean {
    
            if (sessionStorage.getItem('id') == null) {
                this.router.navigate(['home']);
                return false;
            }
            return true;
        }
    }
    

    This is how you can implement auth guard in your code.