J King J King - 1 month ago 25
TypeScript Question

Why does route guard canLoad not fire, but canActiavte does

I have an angular 2.0.1 (final) app that uses HashLocationStrategy for the route navigation strategy.

I define one of my routes as follows:

{
path: 'shiftmanage', component: ShiftManageComponent,
canLoad: [AuthGuard],
canActivate: [AuthGuard]
},


Here is the AuthGuard Class:

import { Injectable } from '@angular/core';
import {
Route,
Router,
CanLoad,
CanActivate,
ActivatedRouteSnapshot,
RouterStateSnapshot } from '@angular/router';

@Injectable()
export class AuthGuard implements CanLoad, CanActivate {
constructor(private router: Router) {
console.log("AuthGuard constructor")
}

canLoad(route: Route): boolean {
if (route.path === "shifts") {
return true;
} else {
return false;
}
}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (route.routeConfig.path === "shiftmanage") {
return true;
} else {
return false;
}
}
}


and I add this guard class to the NgModule Providers like so:

providers: [
AuthGuard,
{ provide: LocationStrategy, useClass: HashLocationStrategy }
... other providers
]


The navigation works and the canActivate route guard is hit whenever I try to navigate to the shiftmanage path.

PROBLEM: The canLoad route guard is never hit.

QUESTION:



Is this canLoad guard not being hit because of the HashLocationStrategy or is there something else I am doing wrong?

Answer

canLoad is used for loading lazy-loaded modules with loadChildred

{
  path: 'child',
  canLoad: [AuthGuard],
  loadChildren: 'path/to/child.module'
}