CanLoad Guard In Angular

CanLoad Guard In Angular

In this article, we will learn how to use Angular CanLoad Guard with an example. The Angular Route Guards are used to restrict the user's ability to browse to or away from a specific route. The CanLoad guard checks to see if a lazy loaded child route can be loaded.

Angular modules can be loaded either eagerly or slowly. Angular loads all modules eagerly by default. To load a module in a sluggish manner, we must use the load method. Children are included in the route definition.

The following path, for example, loads the AdminModule slowly. When the user navigates to the admin route, Angular loads it.

{path: "admin", loadChildren:'./admin/admin.module#AdminModule'},

We may wish to prohibit unauthorized users from loading modules. This is when the CanLoad Guard comes in handy.

CanLoad Guard

The CanLoad Guard prohibits the Lazy Loaded Module from being loaded. This guard is typically used when we don't want an unauthorized user to be able to navigate to any of the module's routes or even access the source code.

CanActivate Guard is a feature of Angular that stops unauthorized users from accessing the route. It does not, however, prevent the module from being downloaded. The source code can be viewed using the Chrome Developer Console. The module cannot be downloaded because of the CanLoad Guard.

How to use CanLoad Guard

To begin, we must develop an Angular Service that implements the CanLoad Interface.

The canLoad method must be implemented by the service. Either true or false must be returned by this method. If canLoad returns true, Angular evaluates it and loads the lazy loaded module.

@Injectable()
export class AuthGuardService implements CanLoad {
  constructor(private router: Router) {
  }
 
  canLoad(route: Route): boolean {
    
    //determine whether you want to load the module
    //return true or false
 
    return true; 
  }
} 

The Service must then be registered in the Root Module.

@NgModule({
  declarations: [
    AppComponent, 
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
  ],
  providers: [AuthGuardService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Finally, as illustrated below, we must add guards to the lazy-loaded routes. It's worth noting that you can create several CanLoad guards; each guard will run in the order in which they were placed.

{path: "admin", loadChildren:'./admin/admin.module#AdminModule', canLoad:[AuthGuardService]},

CanLoad Guard Example

Create a new Angular app with the AdminModule and TestModule modules. Let's create a CanLoad Guard that prevents the AdminModule from loading.

First, as shown below, we create an AuthGuardService that implements the CanLoad Interface.

If the route is admin, return false in the canLoad function; otherwise, return true. In a real-world application, dependency injection can be used to inject the authentication service and check whether or not the user is authorized.

import { Injectable }       from '@angular/core';
import { CanLoad, Route, Router } from '@angular/router';
 
@Injectable()
export class AuthGuardService implements CanLoad {
  
  constructor(private router: Router) {
  }
 
  canLoad(route: Route): boolean {
    
    let url: string = route.path;
    console.log('Url:'+ url);
    if (url=='admin') {
      alert('You are not authorised to visit this page');
      return false;
    }  
    return true; 
  }
} 

Then, under canLoad, include AuthGuardService in the route definition.

const routes: Routes = [
  {path: "admin", loadChildren:'./admin/admin.module#AdminModule', canLoad:[AuthGuardService]},
  {path: "test", loadChildren:'./test/test.module#TestModule', canLoad:[AuthGuardService]},
];

Finally, in the AppModule, register the service.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
 
import { AppRoutingModule } from './app-routing.module';
 
import { AppComponent } from './app.component';
import { AuthGuardService } from './auth-gaurd.service';
 
@NgModule({
  declarations: [
    AppComponent, 
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
  ],
  providers: [AuthGuardService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Run the application, When you open the developer console, you'll notice that only the test module has been downloaded, not the admin module.

CanLoad Guard Example In Angular

The following code is the complete code of the example

Add the following code under the app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
 
import { AppRoutingModule } from './app-routing.module';
 
import { AppComponent } from './app.component';
import { AuthGuardService } from './auth-gaurd.service';
 
 
@NgModule({
  declarations: [
    AppComponent, 
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
  ],
  providers: [AuthGuardService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Add the following code under the app.component.ts:

import { Component } from '@angular/core';
 
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Module Demo';
}

Add the following code under the app.component,html:

<ul>
    <li>
      <a class="navbar-brand" routerlink="">home</a>
    </li>
    <li>
      <a class="navbar-brand" routerlink="/admin/dashboard">Admin</a>
    </li>
    <li>
      <a class="navbar-brand" routerlink="/test">Test</a>
  </li>
  
  </ul>
 
<h1>Angular CanLoad Guard Example</h1>
 
<router-outlet></router-outlet>

Add the following code under the app.component.ts:

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333333;
}
 
li {
    float: left;
}
 
li a {
    display: block;
    color: white;
    text-align: center;
    padding: 16px;
    text-decoration: none;
}
 
li a:hover {
    background-color: #111111;
}

Add the following code under the app.routing.module.ts:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuardService } from './auth-gaurd.service';
 
 
const routes: Routes = [
  {path: "admin", loadChildren:'./admin/admin.module#AdminModule', canLoad:[AuthGuardService]},
  {path: "test", loadChildren:'./test/test.module#TestModule', canLoad:[AuthGuardService]},
];
 
 
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Add the following code under the auth-gaurd.service.ts:

import { Injectable }       from '@angular/core';
import { CanLoad, Route, Router } from '@angular/router';
 
 
@Injectable()
export class AuthGuardService implements CanLoad {
  constructor(private router: Router) {
  }
 
 
  canLoad(route: Route): boolean {
    
    let url: string = route.path;
    console.log('Url:'+ url);
    if (url=='admin') {
      alert('You are not authorised to visit this page');
      return false;
    }
 
    //det
    
    return true; 
  }
  
} 

Add the following code under the admin/admin.module.ts:

import { NgModule } from '@angular/core';
 
import { AdminRoutingModule } from './admin.routing.module';
import { DashboardComponent } from './dashboard.component';
 
 
@NgModule({
  declarations: [DashboardComponent],
  imports: [
    AdminRoutingModule,
  ],
  providers: [],
})
export class AdminModule { }

Add the following code under the admin/admin.routing,module.ts:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
 
import { DashboardComponent } from './dashboard.component';
 
 
 
const routes: Routes = [
    { path: 'dashboard', component: DashboardComponent},
    { path: '', redirectTo:'dashboard'}
];
 
 
@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class AdminRoutingModule { }

Add the following code under the admin/dashboard.component.ts:

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

@Component({
  template: `<h1>Dashboard Component</h1>`,
})
export class DashboardComponent {
  title = '';
}

Add the following code under the test/test.module.ts:

import { NgModule } from '@angular/core';
 
import { TestRoutingModule } from './test.routing.module';
import { TestComponent } from './test.component';
 
 
@NgModule({
  declarations: [TestComponent],
  imports: [
    TestRoutingModule,
  ],
  providers: [],
})
export class TestModule { }

Add the following code under the test/test.routing.module.ts:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
 
import { TestComponent  } from './test.component';
 
 
const routes: Routes = [
    { path: 'list', component: TestComponent},
    { path: '', redirectTo:'list'},
];
 
 
@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class TestRoutingModule { }

Add the following code under the test/test.component.ts:

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

@Component({
  template: `<h1>Test Component</h1>`,
})
export class TestComponent {
  title = '';
}

Conclusion

In this article, we will learn how to use Angular Canload Guard with an example.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post