Monday, May 23, 2022
HomeError SolveHow to implement Auth Guard in Angular

How to implement Auth Guard in Angular

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

File Name:- Security.token.ts

import { Injectable } from '@angular/core';
import {
  ActivatedRouteSnapshot,
  CanActivate,
  Router,
  RouterStateSnapshot,
  UrlTree,
} from '@angular/router';
import { Observable } from 'rxjs';

export class Security {
  token: string = '';
}

@Injectable()
export class MyAuthGuard implements CanActivate {
  constructor(private _router: Router, public _token: Security) {}
  canActivate(
    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;
    }
    this._router.navigate(['/login']);
    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 },
];

@NgModule({
  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.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments