-
Notifications
You must be signed in to change notification settings - Fork 256
Expand file tree
/
Copy pathrouter-utils.ts
More file actions
45 lines (42 loc) · 1.14 KB
/
router-utils.ts
File metadata and controls
45 lines (42 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { Router, UrlMatcher, UrlSegment } from '@angular/router';
export function startsWith(prefix: string): UrlMatcher {
return (url: UrlSegment[]) => {
const fullUrl = url.map((u) => u.path).join('/');
if (fullUrl.startsWith(prefix)) {
return { consumed: url };
}
return null;
};
}
export function endsWith(prefix: string): UrlMatcher {
return (url: UrlSegment[]) => {
const fullUrl = url.map((u) => u.path).join('/');
if (fullUrl.endsWith(prefix)) {
return { consumed: url };
}
return null;
};
}
export function connectRouter(
router: Router,
useHash = false,
baseHref?: string
): void {
let url: string;
if (!useHash) {
url = `${location.pathname.substring(1)}${location.search}`;
if (baseHref && url.startsWith(baseHref)) {
url = url.replace(baseHref, '');
}
router.navigateByUrl(url);
window.addEventListener('popstate', () => {
router.navigateByUrl(url);
});
} else {
url = `${location.hash.substring(1)}${location.search}`;
router.navigateByUrl(url);
window.addEventListener('hashchange', () => {
router.navigateByUrl(url);
});
}
}