MCPcopy
hub / github.com/angular/angular / setUpLocationSync

Function setUpLocationSync

packages/router/upgrade/src/upgrade.ts:74–123  ·  view source on GitHub ↗
(
  ngUpgrade: UpgradeModule,
  urlType: 'path' | 'hash' = 'path',
)

Source from the content-addressed store, hash-verified

72 * @publicApi
73 */
74export function setUpLocationSync(
75 ngUpgrade: UpgradeModule,
76 urlType: 'path' | 'hash' = 'path',
77): void {
78 if (!ngUpgrade.$injector) {
79 throw new Error(`
80 RouterUpgradeInitializer can be used only after UpgradeModule.bootstrap has been called.
81 Remove RouterUpgradeInitializer and call setUpLocationSync after UpgradeModule.bootstrap.
82 `);
83 }
84
85 const router: Router = ngUpgrade.injector.get(Router);
86 const location: Location = ngUpgrade.injector.get(Location);
87
88 ngUpgrade.$injector
89 .get('$rootScope')
90 .$on(
91 '$locationChangeStart',
92 (
93 event: any,
94 newUrl: string,
95 oldUrl: string,
96 newState?: {[k: string]: unknown} | RestoredState,
97 oldState?: {[k: string]: unknown} | RestoredState,
98 ) => {
99 // Navigations coming from Angular router have a navigationId state
100 // property. Don't trigger Angular router navigation again if it is
101 // caused by a URL change from the current Angular router
102 // navigation.
103 const currentNavigationId = router.getCurrentNavigation()?.id;
104 const newStateNavigationId = newState?.navigationId;
105 if (newStateNavigationId !== undefined && newStateNavigationId === currentNavigationId) {
106 return;
107 }
108
109 let url;
110 if (urlType === 'path') {
111 url = resolveUrl(newUrl);
112 } else if (urlType === 'hash') {
113 // Remove the first hash from the URL
114 const hashIdx = newUrl.indexOf('#');
115 url = resolveUrl(newUrl.substring(0, hashIdx) + newUrl.substring(hashIdx + 1));
116 } else {
117 throw 'Invalid URLType passed to setUpLocationSync: ' + urlType;
118 }
119 const path = location.normalize(url.pathname);
120 router.navigateByUrl(path + url.search + url.hash);
121 },
122 );
123}
124
125/**
126 * Normalizes and parses a URL.

Callers 2

upgrade.spec.tsFile · 0.90

Calls 7

getCurrentNavigationMethod · 0.80
indexOfMethod · 0.80
resolveUrlFunction · 0.70
getMethod · 0.65
$onMethod · 0.65
normalizeMethod · 0.65
navigateByUrlMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…