Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Angular canactivate guard example

Suggested Videos
Part 54 - Angular resolve guard | Text | Slides
Part 55 - Angular router navigation events | Text | Slides
Part 56 - Angular route loading indicator | Text | Slides

In this video we will discuss implementing CanActivate guard in Angular with an example.


As the name implies CanActivate guard determines if a route can be activated. There are several use cases for CanActivate guard.
  • We can use it to check if the user is authenticated before allowing him to access protected areas of the application. If he is not authenticated, we redirect him to AccessDenied component or Login component.
  • Similarly we can use it to check, if a specific resource he is looking for exists. if the resource does not exist we redirect him to the PageNotFound component. If the resource exists, we redirect the user to navigate the resource.

In our example, we use a URL as shown below to access a specific employee details. The number 1 in the URL is the employee ID.
http://localhost:4200/employees/1

There is nothing stopping the end user from typing an employee id in the URL that does not exist. So here is what we want to do. 

If the employee with the specified id in the URL exists, then the navigation should be allowed to continue and view that specific employee details. On the other hand, if the employee does not exist, then it should redirect the user to pageNotFound component.

Angular canactivate guard example

Use the following Angular CLI command to generate pageNotFound component. This command also updates the Root module file to import this newly generated component and add it to the declarations array.

ng g c pageNotFound --flat

Include the following <h1> element in page-not-found.component.html file
<h1>The resource you are looking for cannot be found</h1>

Include the following style for <h1> element in page-not-found.component.css file
h1{
    color: red
}

In the root module file, app.module.ts include a route for pageNotFound component.
const appRoutes: Routes = [
  {
    path: 'list',
    component: ListEmployeesComponent,
    resolve: { employeeList: EmployeeListResolverService }
  },
  {
    path: 'create',
    component: CreateEmployeeComponent,
    canDeactivate: [CreateEmployeeCanDeactivateGuardService]
  },
  { path: 'employees/:id', component: EmployeeDetailsComponent },
  { path: '', redirectTo: '/list', pathMatch: 'full' },
  { path: 'notfound', component: PageNotFoundComponent },
];

At this point if you navigate to http://localhost:4200/notfound, you will see pageNotFound component.

Now let's implement CanActivate guard. This guard should check if the employee with the specified id in the URL exists. If the employee does not exist, then it should redirect the user to pageNotFound component. If the employee exists, then it should allow the navigation to continue and view that specific employee details.

Step 1 : Add a new file to the "employees" folder. Name it employee-details-guard.service.ts. Copy and paste the following code.
import {
    CanActivate, Router,
    ActivatedRouteSnapshot,
    RouterStateSnapshot
} from '@angular/router';
import { Injectable } from '@angular/core';
import { EmployeeService } from './employee.service';

@Injectable()
// Make the class implement CanActivate interface as
// we are implementing CanActivate guard service
export class EmployeeDetailsGuardService implements CanActivate {
    constructor(private _employeeService: EmployeeService,
        private _router: Router) { }

    // Provide implementation for canActivate() method of CanActivate interface
    // Return true if navigation is allowed, otherwise false
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        const employeeExists = !!this._employeeService.getEmployee(+route.paramMap.get('id'));

        if (employeeExists) {
            return true;
        } else {
            this._router.navigate(['/notfound']);
            return false;
        }
    }
}

Step 2 : Register the guard with angular dependency injection system : Since CanActivate guard is implemented as a service, we need to register it in a module. At the moment we have only one module in our application and that is the root module AppModule. Import and register EmployeeDetailsGuardService in app.module.ts file using the providers property. 
import { EmployeeDetailsGuardService } from './employees/employee-details-guard.service';

@NgModule({
  declarations: […
  ],
  imports: […
  ],
  providers: [EmployeeDetailsGuardService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 3 : Tie the guard to a route : We want to guard navigation to employee details, so tie the route guard with the "employees/:id" route in app.module.ts file as shown below. 
const appRoutes: Routes = [
  {
    path: 'list',
    component: ListEmployeesComponent,
    resolve: { employeeList: EmployeeListResolverService }
  },
  {
    path: 'create',
    component: CreateEmployeeComponent,
    canDeactivate: [CreateEmployeeCanDeactivateGuardService]
  },
  {
    path: 'employees/:id',
    component: EmployeeDetailsComponent,
    canActivate: [EmployeeDetailsGuardService]
  },
  { path: '', redirectTo: '/list', pathMatch: 'full' },
  { path: 'notfound', component: PageNotFoundComponent },
];

angular crud tutorial

1 comment:

  1. Hi Sir,I Want to see your face-cam video tutorial,

    ReplyDelete

It would be great if you can help share these free resources