Return to site

ANGULAR INTERVIEW QUESTION: Can you explain the role of Angular Guards?

The Angular Guards are interfaces that tell the router if it allows or not the user to go a given URL.

To make that decision, Angular relies on a class implementing the Guards interface and outputs true or false.

There are five kinds of Guards:

  • CanActivate: This Guard is called for each access request, and allow or forbid the access to the user.
  • CanActivateChild: Same as previous one, but for child routes.
  • CanDeactivate: This Guard is called each time a user wishes to leave the current route (for saving a form data when a user leaves early).
  • CanLoad: This Guard checks if a user can access a lazily loaded module route.
  • Resolve: This Guard allows to fetch some data before going to a given route.
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router'
import { AuthService } from './auth.service'

@Injectable({
 providedIn: 'root'
})
export class AuthGuardService implements CanActivate {

 constructor(public auth: AuthService, public router:Router){}
 
 canActivate(): boolean {
  if (!this.auth.isAuthenticated()){
     this.router.navigate(['login']);
     return false;
  }
  return true;
 }

}

 

 

Section image