Last active
February 2, 2021 15:54
-
-
Save anein/fba647b4206695d109c30e1fc0d2e8ee to your computer and use it in GitHub Desktop.
Angular2 Router with the url matcher.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function MyAwesomeMatcher ( url: UrlSegment[] ): UrlMatchResult { | |
if (url.length === 0) { | |
return null; | |
} | |
const reg = /^(awesome-path)$/; | |
const param = url[ 0 ].toString(); | |
if (param.match( reg )) { | |
// myValue: "awesome-path" | |
return ({ consumed: url, posParams: { myValue: url[ 0 ] } }); | |
} | |
return null; | |
} | |
// define application routes. | |
const routes: Routes = [ | |
{ path: '', component: HomeComponent, pathMatch: 'full' }, | |
// { path: 'awesome-path', component: MyAwesomeComponent }, | |
{ matcher: MyAwesomeMatcher, component: MyAwesomeComponent } | |
... | |
]; |
Do you know if it's possible to have an async return value in form of Promise or Observable?
@lazarljubenovic The matching engine checks each route consistently, one by one, that's why the matcher must return either null or the "UrlMatchResult" object. In other words, this indicates that the given path coincided(or not) with a particular route and that the router can continue the work.
@MarcBrillault You're welcome!
Thank you. This really helped. Is there a better way to do this path matching?
Hey friend,
what is the meaning of below lines.could you describe more:-
return ({ consumed: url, posParams: { myValue: url[ 0 ] } });
can you give me any example just for understanding
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
Thanks a lot ! You really helped me there.