diff --git a/docs/routing.md b/docs/routing.md index 7a68a9c6..152305a7 100644 --- a/docs/routing.md +++ b/docs/routing.md @@ -32,4 +32,22 @@ this.tokenService.signIn({ }, error => console.log(error) ); -``` \ No newline at end of file +``` + +Angular-Token implements the `CanLoad` interface, so it can directly be used as a route guard on lazy loading modules. +If the `signInRedirect` option is set the user will be redirected on a failed (=false) CanLoad using `Router.navigate()`. +It currently does not distinguish between user types. + +#### Example: +```javascript +const routerConfig: Routes = [ + { + path: '', + component: PublicComponent + }, { + path: 'restricted', + loadChildren: './restrictedmodule_path/restricted.module#RestrictedModule', + canLoad: [AngularTokenService] + } +]; +``` diff --git a/projects/angular-token/src/lib/angular-token.service.ts b/projects/angular-token/src/lib/angular-token.service.ts index c230efce..70332824 100755 --- a/projects/angular-token/src/lib/angular-token.service.ts +++ b/projects/angular-token/src/lib/angular-token.service.ts @@ -1,5 +1,6 @@ import { Injectable, Optional, Inject, PLATFORM_ID } from '@angular/core'; -import { ActivatedRoute, Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; +import { ActivatedRoute, Router, CanLoad, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, +Route, UrlSegment } from '@angular/router'; import { HttpClient, HttpResponse, HttpErrorResponse } from '@angular/common/http'; import { isPlatformServer } from '@angular/common'; @@ -25,7 +26,7 @@ import { @Injectable({ providedIn: 'root', }) -export class AngularTokenService implements CanActivate { +export class AngularTokenService implements CanActivate, CanLoad { get currentUserType(): string { if (this.userType.value != null) { @@ -145,6 +146,18 @@ export class AngularTokenService implements CanActivate { } } + canLoad(route: Route, segments: UrlSegment[]): boolean { + if (this.userSignedIn()) { + return true; + } else { + // Redirect user to sign in if signInRedirect is set + if (this.router && this.options.signInRedirect) { + this.router.navigate([this.options.signInRedirect]); + } + return false; + } + } + canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { if (this.userSignedIn()) { return true;