From d87285c363b3f892a5afe625f39f4713d350d2f8 Mon Sep 17 00:00:00 2001 From: Konstantin Kharitonov Date: Thu, 8 Dec 2022 01:01:55 +0100 Subject: [PATCH] fix(common): Update `Location` to get a normalized URL valid in case a represented URL starts with the substring equals `APP_BASE_HREF` (#48394) ```ts @NgModule({ imports: [RouterModule.forRoot([{path: '/enigma', component: EnigmaComponent}])], providers: [{provide: APP_BASE_HREF, useValue: '/en'}] }) export class AppModule {} ``` Navigating to `/enigma` will redirect to `/en/igma` not to `/en/enigma` as it expects Fixes: #45744 PR Close #48394 --- packages/common/src/location/location.ts | 5 ++++- packages/common/test/location/location_spec.ts | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/packages/common/src/location/location.ts b/packages/common/src/location/location.ts index 2d52712538d..2c00e5f5b40 100644 --- a/packages/common/src/location/location.ts +++ b/packages/common/src/location/location.ts @@ -301,7 +301,10 @@ export function createLocation() { } function _stripBasePath(basePath: string, url: string): string { - return basePath && url.startsWith(basePath) ? url.substring(basePath.length) : url; + if (basePath === url) { + return ''; + } + return basePath && url.startsWith(basePath + '/') ? url.substring(basePath.length) : url; } function _stripIndexHtml(url: string): string { diff --git a/packages/common/test/location/location_spec.ts b/packages/common/test/location/location_spec.ts index 74cdca9f21a..8622304fb93 100644 --- a/packages/common/test/location/location_spec.ts +++ b/packages/common/test/location/location_spec.ts @@ -266,4 +266,18 @@ describe('Location Class', () => { expect(location.normalize(url)).toBe(route); }); }); + + describe('location.normalize(url) should return correct route', () => { + it('in case url starts with the substring equals APP_BASE_HREF', () => { + const baseHref = '/en'; + const url = '/enigma'; + + TestBed.configureTestingModule({providers: [{provide: APP_BASE_HREF, useValue: baseHref}]}); + + const location = TestBed.inject(Location); + + expect(location.normalize(url)).toBe(url); + expect(location.normalize(baseHref + url)).toBe(url); + }); + }); });