( ngUpgrade: UpgradeModule, urlType: 'path' | 'hash' = 'path', )
| 72 | * @publicApi |
| 73 | */ |
| 74 | export 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. |
no test coverage detected
searching dependent graphs…