Angular CanActivate Guard Example

Angular comes with built-in feature called Route Guards, which helps to control navigation to certain routes. One of the route guards, the CanActivate guard, allows the user to navigate to a particular route based on certain criteria. CanActivate guard is a class that implements the CanActivate interface and has a canActivate() method that returns either a boolean value or an Observable or Promise that resolves to a boolean value. CanActivate guard is mostly used when we want to determine if a user is allowed to access a certain route or not. In this article, we’ll go through an example of using CanActivate guard in angular application.

Example

Let’s create an example where we want to protect a route and allow access to it only if the user is logged in. We’ll create a login service that will have a boolean property isLoggedIn which will be true if the user is logged in and false otherwise. Now, we need to create a CanActivate guard that will check if the user is logged in before allowing them to access the protected route. Let’s start by creating the login service:

LoginService.ts


import { Injectable } from '@angular/core';

@Injectable({
providedIn: 'root'
})
export class LoginService {
isLoggedIn = false;
}

Now, we need to create the CanActivate guard by implementing the CanActivate interface and injecting our login service.

AuthGuard.ts


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

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

constructor(private loginService: LoginService, private router: Router) { }

canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable | Promise | boolean | UrlTree {
if (!this.loginService.isLoggedIn) {
this.router.navigate(['/login']);
return false;
}
return true;
}

}

The canActivate() method takes two arguments:

  • next: ActivatedRouteSnapshot
  • state: RouterStateSnapshot

The ActivatedRouteSnapshot is the current snapshot of the activated route and the RouterStateSnapshot is the state of the router at the current moment. The canActivate() method returns either a boolean value or an Observable or Promise that resolves to a boolean value. If the canActivate() method returns a boolean value, it means the user is either allowed to navigate to the new route or not. In our case, if the user is not logged in, we redirect them to the login page and return false.

Now that we have our CanActivate guard, we can use it to protect a route. For example:

app-routing.module.ts


import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { AuthGuard } from './auth.guard';

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

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

In the above example, we are protecting the home route by adding the canActivate: [AuthGuard] property.

FAQs

What is canActivate guard in Angular?

CanActivate guard is a class that implements the CanActivate interface and has a canActivate() method that returns either a boolean value or an Observable or Promise that resolves to a boolean value. CanActivate guard is mostly used when we want to determine if a user is allowed to access a certain route or not.

How to create a canActivate guard in Angular?

To create a CanActivate guard in Angular, we need to create a class that implements the CanActivate interface and has a canActivate() method that returns either a boolean value or an Observable or Promise that resolves to a boolean value. We can inject services, dependencies or other guards as required.

How to use canActivate guard in Angular?

To use a CanActivate guard in Angular, we need to add the canActivate property to the route definition and set it to an array of guard classes that we want to apply. For example:


{ path: 'home', component: HomeComponent, canActivate: [AuthGuard] },

In the above example, we are using the AuthGuard CanActivate guard to protect the home route.

What is the difference between CanActivate and CanActivateChild guards?

The CanActivate guard is used to control navigation to a particular route. The CanActivateChild guard is used to control navigation to the child routes of a particular route. CanActivateChild guard is used when we want to protect child routes of a particular route.

Similar Posts