In Angular 5 Use Of Router Guards

Few days ago I discussed on the how to set route in Angular5. In this article I discussion on How to setup Router Guards for Router. Now-a-days application have user role base. So particular type of user visit some of the page not other pages. It meas we need to restrict to user visit some of the page for that we need to router guards.


In Angular there are mainly 4 types Guard available.

  1. CanActivate
    This guard decide user can visit this route or not.
  2. CanActivateChild
    It checked If Router has child and they visit that child or not.
  3. CanDeactivate
    It trigger when user exit that route.
  4. CanLoad
    User can route module that layz loaded.

We can add multiple guard for route. In Route path we add parameter of any of the 4 guard then in array we can define service. We can add like below syntax.

canActivate: [servicename1,servicename2]

Router Guards are implemented using services so we need to add that in providers in module.
Router Guards returns Observable, promise & Boolean results.
Let’s create Service for the Router Guard called “AuthLoginGuard”.


import { Injectable } from '@angular/core';
import {CanActivate} from "@angular/router";

@Injectable()
export class AuthLoginGuard implements CanActivate {

  constructor() { 
  }
   canActivate() {

    console.log("authlolgin");
    return true;
  }

}

Now in module.ts file we need to import this service.


import { AuthLoginGuard } from './services/authloginguard';
@NgModule({
  .
  .
  providers: [
    AuthLoginGuard,
   .
   .
  ]
})



In our app.routing.module file where we need first import service added guard in router. display in below example code.


import { AuthLoginGuard } from './services/authloginguard';

const routes:Routes=[
    {'path':'',redirectTo: "signup",pathMatch: 'full'},
    {'path':'signup',
      canActivate:[AuthLoginGuard],
      component: SignupComponent
  },
    {'path':'test',component: TestComponent}
];

In above code you can see the “canActivate” Guard added in signup Route. So when Signup form route called first it checks the Guard if it pass then it will display the route. if fails then it throws error and send user to any pages that you wish. If you have any issue with “canActivate” Guard then please comment we can solve issue. next article we discussion on other Guards.

Spread the love
  • 90
  •  
  •  
  •  
  • 2
  • 1
  •  
  •