How to use CanActivate guard in Angular

CanActivate guards provide route-level protection in Angular applications by controlling access based on authentication, authorization, or custom business logic. As the creator of CoreUI with extensive Angular experience since 2014, I’ve implemented CanActivate guards in countless enterprise applications for security and access control. The most robust approach implements the CanActivate interface with conditional logic that returns boolean, Observable, or Promise values. This pattern enables fine-grained route protection while maintaining clean separation between routing and business logic.

Implement the CanActivate interface in a guard service and apply it to routes in your routing configuration.

import { Injectable } from '@angular/core'
import { CanActivate, Router, ActivatedRouteSnapshot } from '@angular/router'
import { Observable } from 'rxjs'
import { AuthService } from './auth.service'

@Injectable({
  providedIn: 'root'
})
export class AdminGuard implements CanActivate {
  constructor(
    private authService: AuthService,
    private router: Router
  ) {}

  canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
    return this.authService.hasRole('admin').pipe(
      map(hasAdminRole => {
        if (hasAdminRole) {
          return true
        } else {
          this.router.navigate(['/unauthorized'])
          return false
        }
      })
    )
  }
}

// In routing configuration
{
  path: 'admin',
  component: AdminComponent,
  canActivate: [AdminGuard]
}

This code creates a CanActivate guard that checks if the user has admin role before allowing route access. The guard returns an Observable from the auth service, automatically handling async role verification. If authorization fails, it redirects to an unauthorized page and blocks access. The guard is applied to routes using the canActivate property in the route configuration.

Best Practice Note:

This is the authorization pattern we use in CoreUI Pro admin templates for role-based access control. CanActivate guards can return boolean, Observable, or Promise for synchronous and asynchronous authorization scenarios.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to round a number to two decimal places in JavaScript
How to round a number to two decimal places in JavaScript

How to sleep in Javascript
How to sleep in Javascript

Mastering Inline Styles in React.js: Enhancing Your Components with Style
Mastering Inline Styles in React.js: Enhancing Your Components with Style

How to Open Link in a New Tab in HTML?
How to Open Link in a New Tab in HTML?

Answers by CoreUI Core Team