How to implement Auth Guard in Angular

Auth Guard in Angular, Read below steps to get more details !!!!

Step 1) Create a Service file in your angular project.

File Name:- Security.token.ts

import { Injectable } from '@angular/core';
import {
} from '@angular/router';
import { Observable } from 'rxjs';

export class Security {
  token: string = '';

export class MyAuthGuard implements CanActivate {
  constructor(private _router: Router, public _token: Security) {}
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
    | boolean
    | UrlTree
    | Observable<boolean | UrlTree>
    | Promise<boolean | UrlTree> {
    // throw new Error("Method not implemented.");
    if (this._token.token.length != 0) {
      return true;
    return false;

Step 2) Make sure that you have specified your MyAuth Guard in your Module.ts file.

 providers: [Security, MyAuthGuard],

Step 3) Open your Routing file and on which page you want to apply the Authentication specified in the below code.

const routes: Routes = [
  { path: '', pathMatch: 'full', redirectTo: 'home' },
  { path: 'home', component: HomeComponent },
  { path: 'add', component: AddComponent, canActivate: [MyAuthGuard] },
  { path: 'login', component: LoginComponent },

  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
export class AppRoutingModule {}

Now in the above code, I have applied the MyAuthGuard on AddComponent page, but on the HOME AND Login page, I am not interested in applying.

Leave a Comment