From 4d2901d4808ef8d970cee49ad05341c5e63bb1a7 Mon Sep 17 00:00:00 2001 From: Dzmitry Shylovich Date: Sun, 15 Jan 2017 01:05:24 +0300 Subject: [PATCH] fix(router): fix navigation from the root component ngOnInit hook (#13932) Closes #13795 PR Close #13932 --- modules/@angular/router/src/router.ts | 4 +++- .../@angular/router/test/integration.spec.ts | 21 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/modules/@angular/router/src/router.ts b/modules/@angular/router/src/router.ts index ce7b9c8d29..a926b52f6d 100644 --- a/modules/@angular/router/src/router.ts +++ b/modules/@angular/router/src/router.ts @@ -364,7 +364,9 @@ export class Router { */ initialNavigation(): void { this.setUpLocationChangeListener(); - this.navigateByUrl(this.location.path(true), {replaceUrl: true}); + if (this.navigationId === 0) { + this.navigateByUrl(this.location.path(true), {replaceUrl: true}); + } } /** diff --git a/modules/@angular/router/test/integration.spec.ts b/modules/@angular/router/test/integration.spec.ts index 31fb4cef99..ac14a1e9b9 100644 --- a/modules/@angular/router/test/integration.spec.ts +++ b/modules/@angular/router/test/integration.spec.ts @@ -37,6 +37,18 @@ describe('Integration', () => { expect(location.path()).toEqual('/simple'); }))); + it('should navigate from ngOnInit hook', + fakeAsync(inject([Router, Location], (router: Router, location: Location) => { + router.resetConfig([ + {path: '', component: SimpleCmp}, + {path: 'one', component: RouteCmp}, + ]); + + const fixture = createRoot(router, RootCmpWithOnInit); + expect(location.path()).toEqual('/one'); + expect(fixture.nativeElement).toHaveText('route'); + }))); + describe('should execute navigations serially', () => { let log: any[] = []; @@ -2868,6 +2880,13 @@ class ComponentRecordingRoutePathAndUrl { class RootCmp { } +@Component({selector: 'root-cmp-on-init', template: ``}) +class RootCmpWithOnInit { + constructor(private router: Router) {} + + ngOnInit(): void { this.router.navigate(['one']); } +} + @Component({ selector: 'root-cmp', template: @@ -2939,6 +2958,7 @@ function createRoot(router: Router, type: any): ComponentFixture { ComponentRecordingRoutePathAndUrl, RouteCmp, RootCmp, + RootCmpWithOnInit, RelativeLinkInIfCmp, RootCmpWithTwoOutlets, EmptyQueryParamsCmp, @@ -2966,6 +2986,7 @@ function createRoot(router: Router, type: any): ComponentFixture { ComponentRecordingRoutePathAndUrl, RouteCmp, RootCmp, + RootCmpWithOnInit, RelativeLinkInIfCmp, RootCmpWithTwoOutlets, EmptyQueryParamsCmp,