Protecting a Lazy-Loaded Module
Explore how to protect lazy-loaded modules in Angular by using authentication guards that implement the CanLoad interface. Understand how to extend auth guards for lazy-loaded routes and apply lazy loading to standalone components with the Angular router by leveraging the loadComponent property. This lesson helps you control access and optimize loading for Angular applications.
We'll cover the following...
Lazy-loaded modules are standard Angular modules, so we can control their access using guards. We can control unauthorized access to a lazy-loaded module similar to how we can do so in eagerly loaded ones. However, our guards need to implement a different interface for this case, the CanLoad interface.
Using a lazy-loading module in auth guard
We will extend our authentication guard for use with lazy-loaded modules.
Open the
auth.guard.tsfile and importCanLoadFnfrom the@angular/routernpm package:
import { CanActivateFn, CanLoadFn, Router } from '@angular/router';
Add the
CanLoadFn...