Skip to content

Commit

Permalink
fix(@schematics/angular): add CanDeactivate guard
Browse files Browse the repository at this point in the history
This generates a generic `CanDeactivate<unknown>` guard.

Fixes angular#15668
  • Loading branch information
cexbrayat committed Nov 14, 2019

Unverified

This user has not yet uploaded their public signing key.
1 parent 1d105eb commit 2a53e03
Showing 4 changed files with 28 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -16,6 +16,13 @@ export class <%= classify(name) %>Guard implements <%= implementations %> {
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return true;
}
<% } %><% if (implements.includes('CanDeactivate')) { %>canDeactivate(
component: unknown,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState?: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return true;
}
<% } %><% if (implements.includes('CanLoad')) { %>canLoad(
route: Route,
segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean {
6 changes: 4 additions & 2 deletions packages/schematics/angular/guard/index.ts
Original file line number Diff line number Diff line change
@@ -35,8 +35,10 @@ export default function (options: GuardOptions): Rule {
throw new SchematicsException('Option "implements" is required.');
}

const implementations = options.implements.join(', ');
let implementationImports = `${implementations}, `;
const implementations = options.implements
.map(implement => implement === 'CanDeactivate' ? 'CanDeactivate<unknown>' : implement)
.join(', ');
let implementationImports = `${options.implements.join(', ')}, `;
// As long as we aren't in IE... ;)
if (options.implements.includes(GuardInterface.CanLoad)) {
implementationImports = `${implementationImports}Route, UrlSegment, `;
1 change: 1 addition & 0 deletions packages/schematics/angular/guard/schema.json
Original file line number Diff line number Diff line change
@@ -59,6 +59,7 @@
"enum": [
"CanActivate",
"CanActivateChild",
"CanDeactivate",
"CanLoad"
],
"type": "string"
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import {join} from 'path';
import {ng} from '../../../utils/process';
import {expectFileToExist,expectFileToMatch} from '../../../utils/fs';


export default async function() {
// Does not create a sub directory.
const guardDir = join('src', 'app');

await ng('generate', 'guard', 'load', '--implements=CanLoad', '--implements=CanDeactivate');
await expectFileToExist(guardDir);
await expectFileToExist(join(guardDir, 'load.guard.ts'));
await expectFileToMatch(join(guardDir, 'load.guard.ts'), /implements CanLoad, CanDeactivate<unknown>/);
await expectFileToExist(join(guardDir, 'load.guard.spec.ts'));
await ng('test', '--watch=false');
}

0 comments on commit 2a53e03

Please sign in to comment.