Skip to content

Commit ae9b4e6

Browse files
observstreamkara
authored andcommitted
fix(router): take base uri into account in setUpLocationSync() (#20244)
Normalize the full URL (including the base uri) before passing it to `router.navigateByUrl()`. Fixes #20061 PR Close #20244
1 parent 478eca3 commit ae9b4e6

8 files changed

Lines changed: 180 additions & 11 deletions

File tree

‎karma-js.conf.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ module.exports = function(config) {
8484
'dist/all/@angular/elements/schematics/**',
8585
'dist/all/@angular/examples/**/e2e_test/*',
8686
'dist/all/@angular/language-service/**',
87-
'dist/all/@angular/router/test/**',
87+
'dist/all/@angular/router/**/test/**',
8888
'dist/all/@angular/platform-browser/testing/e2e_util.js',
8989
'dist/all/angular1_router.js',
9090
'dist/examples/**/e2e_test/**',

‎packages/router/BUILD.bazel‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@ ng_module(
1515
"//packages/common",
1616
"//packages/core",
1717
"//packages/platform-browser",
18-
"//packages/upgrade/static",
1918
"@rxjs",
19+
"@rxjs//operators",
2020
],
2121
)
2222

‎packages/router/karma-test-shim.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,8 @@ System.config({
5151
'@angular/platform-browser': {main: 'index.js', defaultExtension: 'js'},
5252
'@angular/platform-browser-dynamic/testing': {main: 'index.js', defaultExtension: 'js'},
5353
'@angular/platform-browser-dynamic': {main: 'index.js', defaultExtension: 'js'},
54+
'@angular/upgrade/static': {main: 'index.js', defaultExtension: 'js'},
55+
'@angular/router/upgrade': {main: 'index.js', defaultExtension: 'js'},
5456
'@angular/router/testing': {main: 'index.js', defaultExtension: 'js'},
5557
'@angular/router': {main: 'index.js', defaultExtension: 'js'},
5658
'rxjs/ajax': {main: 'index.js', defaultExtension: 'js'},

‎packages/router/karma.conf.js‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,21 +61,24 @@ module.exports = function(config) {
6161
{
6262
pattern: 'dist/all/@angular/platform-browser/testing/**/*.js',
6363
included: false,
64-
watched: false,
64+
watched: false
6565
},
6666

6767
{pattern: 'dist/all/@angular/platform-browser-dynamic/*.js', included: false, watched: false},
6868
{
6969
pattern: 'dist/all/@angular/platform-browser-dynamic/src/**/*.js',
7070
included: false,
71-
watched: false,
71+
watched: false
7272
},
7373
{
7474
pattern: 'dist/all/@angular/platform-browser-dynamic/testing/**/*.js',
7575
included: false,
76-
watched: false,
76+
watched: false
7777
},
7878

79+
{pattern: 'dist/all/@angular/upgrade/static/*.js', included: false, watched: false},
80+
{pattern: 'dist/all/@angular/upgrade/static/src/**/*.js', included: false, watched: false},
81+
7982
// Router
8083
{pattern: 'dist/all/@angular/router/**/*.js', included: false, watched: true}
8184
],

‎packages/router/upgrade/BUILD.bazel‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,17 @@ load("//tools:defaults.bzl", "ng_module")
66

77
ng_module(
88
name = "upgrade",
9-
srcs = glob(["**/*.ts"]),
9+
srcs = glob(
10+
[
11+
"*.ts",
12+
"src/**/*.ts",
13+
],
14+
),
1015
module_name = "@angular/router/upgrade",
1116
deps = [
17+
"//packages/common",
1218
"//packages/core",
1319
"//packages/router",
20+
"//packages/upgrade/static",
1421
],
1522
)

‎packages/router/upgrade/src/upgrade.ts‎

Lines changed: 40 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,11 @@
66
* found in the LICENSE file at https://angular.io/license
77
*/
88

9+
import {Location} from '@angular/common';
910
import {APP_BOOTSTRAP_LISTENER, ComponentRef, InjectionToken} from '@angular/core';
1011
import {Router} from '@angular/router';
1112
import {UpgradeModule} from '@angular/upgrade/static';
1213

13-
14-
1514
/**
1615
* @description
1716
*
@@ -68,11 +67,47 @@ export function setUpLocationSync(ngUpgrade: UpgradeModule) {
6867
}
6968

7069
const router: Router = ngUpgrade.injector.get(Router);
71-
const url = document.createElement('a');
70+
const location: Location = ngUpgrade.injector.get(Location);
7271

7372
ngUpgrade.$injector.get('$rootScope')
7473
.$on('$locationChangeStart', (_: any, next: string, __: string) => {
75-
url.href = next;
76-
router.navigateByUrl(url.pathname + url.search + url.hash);
74+
const url = resolveUrl(next);
75+
const path = location.normalize(url.pathname);
76+
router.navigateByUrl(path + url.search + url.hash);
7777
});
7878
}
79+
80+
/**
81+
* Normalize and parse a URL.
82+
*
83+
* - Normalizing means that a relative URL will be resolved into an absolute URL in the context of
84+
* the application document.
85+
* - Parsing means that the anchor's `protocol`, `hostname`, `port`, `pathname` and related
86+
* properties are all populated to reflect the normalized URL.
87+
*
88+
* While this approach has wide compatibility, it doesn't work as expected on IE. On IE, normalizing
89+
* happens similar to other browsers, but the parsed components will not be set. (E.g. if you assign
90+
* `a.href = 'foo'`, then `a.protocol`, `a.host`, etc. will not be correctly updated.)
91+
* We work around that by performing the parsing in a 2nd step by taking a previously normalized URL
92+
* and assigning it again. This correctly populates all properties.
93+
*
94+
* See
95+
* https://github.com/angular/angular.js/blob/2c7400e7d07b0f6cec1817dab40b9250ce8ebce6/src/ng/urlUtils.js#L26-L33
96+
* for more info.
97+
*/
98+
let anchor: HTMLAnchorElement|undefined;
99+
function resolveUrl(url: string): {pathname: string, search: string, hash: string} {
100+
if (!anchor) {
101+
anchor = document.createElement('a');
102+
}
103+
104+
anchor.setAttribute('href', url);
105+
anchor.setAttribute('href', anchor.href);
106+
107+
return {
108+
// IE does not start `pathname` with `/` like other browsers.
109+
pathname: `/${anchor.pathname.replace(/^\//, '')}`,
110+
search: anchor.search,
111+
hash: anchor.hash
112+
};
113+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
load("//tools:defaults.bzl", "ts_library", "ts_web_test_suite")
2+
3+
ts_library(
4+
name = "test_lib",
5+
testonly = 1,
6+
srcs = glob(["**/*.ts"]),
7+
deps = [
8+
"//packages/common",
9+
"//packages/core/testing",
10+
"//packages/router",
11+
"//packages/router/upgrade",
12+
"//packages/upgrade/static",
13+
],
14+
)
15+
16+
ts_web_test_suite(
17+
name = "test_web",
18+
deps = [
19+
":test_lib",
20+
],
21+
)
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
/**
2+
* @license
3+
* Copyright Google Inc. All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.io/license
7+
*/
8+
9+
import {Location} from '@angular/common';
10+
import {TestBed} from '@angular/core/testing';
11+
import {Router} from '@angular/router';
12+
import {setUpLocationSync} from '@angular/router/upgrade';
13+
import {UpgradeModule} from '@angular/upgrade/static';
14+
15+
describe('setUpLocationSync', () => {
16+
let upgradeModule: UpgradeModule;
17+
let RouterMock: any;
18+
let LocationMock: any;
19+
20+
beforeEach(() => {
21+
RouterMock = jasmine.createSpyObj('Router', ['navigateByUrl']);
22+
LocationMock = jasmine.createSpyObj('Location', ['normalize']);
23+
24+
TestBed.configureTestingModule({
25+
providers: [
26+
UpgradeModule, {provide: Router, useValue: RouterMock},
27+
{provide: Location, useValue: LocationMock}
28+
],
29+
});
30+
31+
upgradeModule = TestBed.get(UpgradeModule);
32+
upgradeModule.$injector = {
33+
get: jasmine.createSpy('$injector.get').and.returnValue({'$on': () => undefined})
34+
};
35+
});
36+
37+
it('should throw an error if the UpgradeModule.bootstrap has not been called', () => {
38+
upgradeModule.$injector = null;
39+
40+
expect(() => setUpLocationSync(upgradeModule)).toThrowError(`
41+
RouterUpgradeInitializer can be used only after UpgradeModule.bootstrap has been called.
42+
Remove RouterUpgradeInitializer and call setUpLocationSync after UpgradeModule.bootstrap.
43+
`);
44+
});
45+
46+
it('should get the $rootScope from AngularJS and set an $on watch on $locationChangeStart',
47+
() => {
48+
const $rootScope = jasmine.createSpyObj('$rootScope', ['$on']);
49+
50+
upgradeModule.$injector.get.and.callFake(
51+
(name: string) => (name === '$rootScope') && $rootScope);
52+
53+
setUpLocationSync(upgradeModule);
54+
55+
expect($rootScope.$on).toHaveBeenCalledTimes(1);
56+
expect($rootScope.$on).toHaveBeenCalledWith('$locationChangeStart', jasmine.any(Function));
57+
});
58+
59+
it('should navigate by url every time $locationChangeStart is broadcasted', () => {
60+
const url = 'https://google.com';
61+
const pathname = '/custom/route';
62+
const normalizedPathname = 'foo';
63+
const query = '?query=1&query2=3';
64+
const hash = '#new/hash';
65+
const $rootScope = jasmine.createSpyObj('$rootScope', ['$on']);
66+
67+
upgradeModule.$injector.get.and.returnValue($rootScope);
68+
LocationMock.normalize.and.returnValue(normalizedPathname);
69+
70+
setUpLocationSync(upgradeModule);
71+
72+
const callback = $rootScope.$on.calls.argsFor(0)[1];
73+
callback({}, url + pathname + query + hash, '');
74+
75+
expect(LocationMock.normalize).toHaveBeenCalledTimes(1);
76+
expect(LocationMock.normalize).toHaveBeenCalledWith(pathname);
77+
78+
expect(RouterMock.navigateByUrl).toHaveBeenCalledTimes(1);
79+
expect(RouterMock.navigateByUrl).toHaveBeenCalledWith(normalizedPathname + query + hash);
80+
});
81+
82+
it('should work correctly on browsers that do not start pathname with `/`', () => {
83+
const anchorProto = HTMLAnchorElement.prototype;
84+
const originalDescriptor = Object.getOwnPropertyDescriptor(anchorProto, 'pathname');
85+
Object.defineProperty(anchorProto, 'pathname', {get: () => 'foo/bar'});
86+
87+
try {
88+
const $rootScope = jasmine.createSpyObj('$rootScope', ['$on']);
89+
upgradeModule.$injector.get.and.returnValue($rootScope);
90+
91+
setUpLocationSync(upgradeModule);
92+
93+
const callback = $rootScope.$on.calls.argsFor(0)[1];
94+
callback({}, '', '');
95+
96+
expect(LocationMock.normalize).toHaveBeenCalledWith('/foo/bar');
97+
} finally {
98+
Object.defineProperty(anchorProto, 'pathname', originalDescriptor !);
99+
}
100+
});
101+
});

0 commit comments

Comments
 (0)