feat(router): add hash-based navigation option to setUpLocationSync (#28609)

The `setUpLocationSync` function in @angular/router/upgrade didn't previously let you sync hash-based navigations. With this change, you can now pass an option to `setUpLocationSync` that will make sure location changes run in Angular in hash-based apps.

Fixes #24429 #21995

PR Close #28609
This commit is contained in:
Jason Aden
2019-02-07 16:13:30 -08:00
committed by Igor Minar
parent 295a143ae0
commit 71d0eeb966
3 changed files with 37 additions and 3 deletions

View File

@ -58,7 +58,7 @@ export function locationSyncBootstrapListener(ngUpgrade: UpgradeModule) {
*
* @publicApi
*/
export function setUpLocationSync(ngUpgrade: UpgradeModule) {
export function setUpLocationSync(ngUpgrade: UpgradeModule, urlType: 'path' | 'hash' = 'path') {
if (!ngUpgrade.$injector) {
throw new Error(`
RouterUpgradeInitializer can be used only after UpgradeModule.bootstrap has been called.
@ -71,7 +71,16 @@ export function setUpLocationSync(ngUpgrade: UpgradeModule) {
ngUpgrade.$injector.get('$rootScope')
.$on('$locationChangeStart', (_: any, next: string, __: string) => {
const url = resolveUrl(next);
let url;
if (urlType === 'path') {
url = resolveUrl(next);
} else if (urlType === 'hash') {
// Remove the first hash from the URL
const hashIdx = next.indexOf('#');
url = resolveUrl(next.substring(0, hashIdx) + next.substring(hashIdx + 1));
} else {
throw 'Invalid URLType passed to setUpLocationSync: ' + urlType;
}
const path = location.normalize(url.pathname);
router.navigateByUrl(path + url.search + url.hash);
});