How to use trying to use these kind of URLs with prefix/foo-bar-1123
, prefix/foo-bar-1123/bazquux-123
with Angular 4 Router? The important bits are the numerical id's which I am trying to capture.
I have tried this, but the result is that I get a all data between // characted captured to single variable called categorySlug-:categoryId
and subcategorySlug-:subcategoryId
.
const routes = [{
path: 'prefix/:categorySlug-:categoryId',
component: MyComponent,
}, {
path: 'prefix/:categorySlug-:categoryId/:subcategorySlug-:subcategoryId',
component: MyComponent,
}]
export const MyRoute: ModuleWithProviders = RouterModule.forChild(routes)
Ultimately I'd like to end up with these kind of variables:
categorySlug=foo-bar
categoryId=1123
subcategorySlug=bazquux
subcategoryId=123
Is this something that the Router supports? Is is possible to extend Router to support these?
Create a custom UrlMatcher which can be used to implement matching and fetch id's from URL. This works at least in Angular 4.4.3.
const categoryUrlMatcher = (url: UrlSegment[], group: UrlSegmentGroup, route: Route): UrlMatchResult => {
if (url.length != 2) {
return null
}
if (url[0].path !== 'prefix') {
return null
}
const categoryMatch = url[1].path.match(/(\w+)-(\d+)$/)
if (categoryMatch) {
return {
consumed: url,
posParams: {
categorySlug: new UrlSegment(categoryMatch[1], {}),
categoryId: new UrlSegment(categoryMatch[2], {})
}}
}
return null
}
const routes: Routes = [
{
matcher: categoryUrlMatcher,
component: MyComponent,
}
]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.