Skip to content

Commit

Permalink
fix: navigation for microrontends
Browse files Browse the repository at this point in the history
  • Loading branch information
Sylvain Marcadal committed Aug 25, 2022
1 parent 6f4ec24 commit dcfddc3
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 9 deletions.
4 changes: 3 additions & 1 deletion libs/mf-tools/src/lib/web-components/bootstrap-utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { APP_BASE_HREF } from '@angular/common';
import {
CompilerOptions,
enableProdMode,
Expand Down Expand Up @@ -211,11 +212,12 @@ function shareShellZone(injector: Injector) {

function connectMicroFrontendRouter(injector: Injector) {
const router = injector.get(Router);
const baseHref = injector.get(APP_BASE_HREF, '/');

if (!router) {
console.warn('No router to connect found');
return;
}

connectRouter(router);
connectRouter(router, false, baseHref);
}
27 changes: 19 additions & 8 deletions libs/mf-tools/src/lib/web-components/router-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,30 @@ export function endsWith(prefix: string): UrlMatcher {
};
}

export function connectRouter(router: Router, useHash = false): void {
let url: string;

function relativePathName(path: string, baseHref: string) {
if (path.startsWith(baseHref)) {
path = path.slice(baseHref.length);
}
return path;
}

function guessRouterUrl(useHash = false, baseHref: string) {
const path = useHash
? location.hash
: relativePathName(location.pathname, baseHref);
return `${path}${location.search}`;
}

export function connectRouter(router: Router, useHash = false, baseHref = '/') {
void router.navigateByUrl(guessRouterUrl(useHash, baseHref));
if (!useHash) {
url = `${location.pathname.substr(1)}${location.search}`;
router.navigateByUrl(url);
window.addEventListener('popstate', () => {
router.navigateByUrl(url);
void router.navigateByUrl(guessRouterUrl(useHash, baseHref));
});
} else {
url = `${location.hash.substr(1)}${location.search}`;
router.navigateByUrl(url);
window.addEventListener('hashchange', () => {
router.navigateByUrl(url);
void router.navigateByUrl(guessRouterUrl(useHash, baseHref));
});
}
}

0 comments on commit dcfddc3

Please sign in to comment.