Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CanLoad interfaz implemented for Lazy Loading modules. #499

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion docs/routing.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,22 @@ this.tokenService.signIn({
},
error => console.log(error)
);
```
```

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]
}
];
```
17 changes: 15 additions & 2 deletions projects/angular-token/src/lib/angular-token.service.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand All @@ -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) {
Expand Down Expand Up @@ -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;
Expand Down