Skip to content

Instantly share code, notes, and snippets.

@MarcBrillault
Last active February 2, 2021 15:55
Show Gist options
  • Save MarcBrillault/87f8df9610cfa3ed112afc3f8da474e8 to your computer and use it in GitHub Desktop.
Save MarcBrillault/87f8df9610cfa3ed112afc3f8da474e8 to your computer and use it in GitHub Desktop.
const appRoutes: Routes = [
{
path: '',
component: HomepageComponent,
},
{
matcher: UrlMatcher,
component: ProductComponent,
},
{
path: '**',
component: Error404Component,
},
];
import { UrlMatchResult, UrlSegment } from '@angular/router';
export function UrlMatcher(url: UrlSegment[], regex: RegExp, capturedParameterNames: string[]): urlMatchResult | null {
if (url.length === 0) {
return null;
}
capturedParameterNames.splice(0, 0, 'fullPath');
let fullPath = '';
let result: RegExpExecArray | null;
for (let i = 0; i < url.length; ++i) {
if (url[i].path) {
fullPath += '/' + url[i].path;
}
}
if (result = regex.exec(fullPath)) {
const posParams: {[p: string]: UrlSegment} = {};
for (let index = 0; index < result.length; index++) {
posParams[capturedParameterNames[index]] = new UrlSegment(result[index], {});
}
return {consumed: url, posParams: posParams};
}
return null;
}
@xavadu
Copy link

xavadu commented Feb 2, 2021

For mine use case where a matcher can have optionally parameter

/**
 * Generic matcher function
 *
 * Set in route data variable with a named regex to get parameters
 * ie:
 * data: {
 *     regex: /^(?<currency_pair>[a-z_]{3,6}-[a-z_]{3,6})?$/
 * }
 */
export function matcher(segments: UrlSegment[], segmentGroup: UrlSegmentGroup, route: Route): UrlMatchResult {
    const regex = route.data.regex;
    const url = segments.length == 1 ? segments[0].toString() : '';

    let params = url.match(regex);
    if (params) {
        const posParams: { [key: string]: UrlSegment } = {};

        // Named parameter based in name group of regexp
        for (const [name, value] of Object.entries(params.groups)) {
            posParams[name] = new UrlSegment(value, {});;
        }

        return { consumed: segments, posParams };
    }

    return null;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment