From 2c006e8fac04225d0694c4e08f2ad42b5822ee02 Mon Sep 17 00:00:00 2001 From: Brandon Date: Wed, 2 Aug 2017 08:56:44 -0500 Subject: [PATCH] fix(RouterStore): Add support for cancellation with CanLoad guard (#223) Closes #213 --- modules/router-store/spec/integration.spec.ts | 41 ++++++++++++++++++- .../router-store/src/router_store_module.ts | 7 +++- 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/modules/router-store/spec/integration.spec.ts b/modules/router-store/spec/integration.spec.ts index a43e8e419a..4a16632a26 100644 --- a/modules/router-store/spec/integration.spec.ts +++ b/modules/router-store/spec/integration.spec.ts @@ -286,10 +286,40 @@ describe('integration spec', () => { done(); }); }); + + it('should support cancellation of initial navigation using canLoad guard', done => { + const reducer = (state: any, action: RouterAction) => { + const r = routerReducer(state, action); + return r && r.state + ? { url: r.state.url, navigationId: r.navigationId } + : null; + }; + + createTestModule({ + reducers: { routerReducer, reducer }, + canLoad: () => false, + }); + + const router = TestBed.get(Router); + const store = TestBed.get(Store); + const log = logOfRouterAndStore(router, store); + + router.navigateByUrl('/load').then((r: boolean) => { + expect(r).toBe(false); + + expect(log).toEqual([ + { type: 'store', state: null }, + { type: 'router', event: 'NavigationStart', url: '/load' }, + { type: 'store', state: null }, + { type: 'router', event: 'NavigationCancel', url: '/load' }, + ]); + done(); + }); + }); }); function createTestModule( - opts: { reducers?: any; canActivate?: Function } = {} + opts: { reducers?: any; canActivate?: Function; canLoad?: Function } = {} ) { @Component({ selector: 'test-app', @@ -314,6 +344,11 @@ function createTestModule( component: SimpleCmp, canActivate: ['CanActivateNext'], }, + { + path: 'load', + loadChildren: 'test', + canLoad: ['CanLoadNext'], + }, ]), StoreRouterConnectingModule, ], @@ -322,6 +357,10 @@ function createTestModule( provide: 'CanActivateNext', useValue: opts.canActivate || (() => true), }, + { + provide: 'CanLoadNext', + useValue: opts.canLoad || (() => true), + }, ], }); diff --git a/modules/router-store/src/router_store_module.ts b/modules/router-store/src/router_store_module.ts index 4f331e9bac..1ee0481841 100644 --- a/modules/router-store/src/router_store_module.ts +++ b/modules/router-store/src/router_store_module.ts @@ -185,7 +185,12 @@ export class StoreRouterConnectingModule { } private navigateIfNeeded(): void { - if (!this.storeState['routerReducer']) return; + if ( + !this.storeState['routerReducer'] || + !this.storeState['routerReducer'].state + ) { + return; + } if (this.dispatchTriggeredByRouter) return; if (this.router.url !== this.storeState['routerReducer'].state.url) {