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.
Is this canLoad guard not being hit because of the HashLocationStrategy or is there something else I am doing wrong?
Well, there is a difference, the canActivate exists to prevent unauthorized users from accessing a route, while canLoad is used to prevent the application from loading an entire module or component in a lazy way (lazy loading) if the user is not authorized.
Difference between CanLoad and CanActivate is, CanLoad avoids loading the module itself when the validation fails but CanActivate loads the module and validates whether it can instantiate the module or not.
Both canActivate and canLoad can be used together.
The differences If we directly navigate to the child route, the canActivate guard will also be executed. canActivateChild will always be executed while navigating to/between child routes. For example, if we're at a child route child/1 and we navigate to child/2 , the guard will get executed.
canLoad
is used for loading lazy-loaded modules with loadChildren
{
path: 'child',
canLoad: [AuthGuard],
loadChildren: 'path/to/child.module'
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With