CanLoad – don't lazy load unless the user has access

Lazy loading is a great feature that can drastically reduce the loading time of your application by ensuring your application only starts with the bundles it absolutely needs. However, even if you ensure that most of your modules are lazy loaded, you need to take it a step further, especially if your application has any authentication or authorization mechanisms in place.  

Consider the following, let us say that more than one of your modules needs the user to be authenticated or to have the role of admin. It would make no sense to load those modules when a user routes to their path if they are not allowed in that area anyway. To remedy this scenario, we can use a guard called CanLoad. CanLoad ensures we first validate whether it makes sense to lazy load a certain module based on a condition. You need to do the following to use this:

  1. Implement the CanLoad interface and the canLoad() method, in a service.
  2. Add the preceding service to the CanLoad property of your route.

The following creates a service that implements the CanLoad interface:

@Injectable()
export class CanLoadService implements CanLoad {
canLoad(route: Route) {
// replace this to check if user is authenticated/authorized
return false;
}
}

As you can see from the code, the canLoad() method returns a Boolean. In this case, we have made it return false, which means the module will not be loaded.

The second thing we needed to do was to update the route to use this service as a  canLoad guard:

{
path: 'lazy',
loadChildren : 'app/lazy/lazy.module#LazyModule',
canLoad: [CanLoadService]
}

If we attempt to surf to localhost:4200/lazy, we go nowhere as our canLoad, by returning false, tells us that we can't. Having a look at our console, we also see the following:

Here, it says it cannot load children due to the guard, so the guard is working.

Notice how everything works fine and loads like it should when you update the CanLoadService and canLoad() method to return true.

Don't forget to add CanLoadService to the providers array of the root module.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset