I am working on an Angular Universal Application. I want to create dynamic routes with custom prefix but I am unable find any helpful documentation related with my case. Any Help will be appreciated...
Details:
What I have is, I have 4 pages with 4 different dynamic URLs which are:
http://example.com/
)http://example.com/{category_name}
)http://example.com/{category_name}/{sub_category_name}
)http://example.com/p{product_id}-{product_name}
)http://example.com/user{user_id}-{user_name}
)What I did
I have registered a single route to handle Home, Category and Sub Category Pages because they have same UI with dynamic category levels mentioned below,
RouterModule.forRoot([
{path: '**', component: HomeComponent, data: {title: 'Home', description: 'Homepage - quick overview.'}}
])
Struggling:
Now, I am unable to add the routes for Product and User Page, I am unable to understand, how to add p
and user
prefixs after slash and before ids
in Product and User Pages respectively. Without these prefixs, routing is working fine.
Examples of Required URLs for Product & User Pages
I am using @angular/router
for routing.
Thanks in advance.
Thanks, @Yuriy to reopen this, I have already got the answer from @Ingo Bürk's comment. The below mentioned Gist helped me to create routes through the regex. https://gist.github.com/matanshukry/22fae5dba9c307baf0f364a9c9f7c115
For reference, I have added the source below,
/**
* Copyright (c) Matan Shukry
* All rights reserved.
*/
import { UrlSegment, UrlSegmentGroup, Route } from '@angular/router';
// export type UrlMatchResult = {
// consumed: UrlSegment[]; posParams?: { [name: string]: UrlSegment };
// };
export function ComplexUrlMatcher(paramName: string, regex: RegExp) {
return (
segments: UrlSegment[],
segmentGroup: UrlSegmentGroup,
route: Route) => {
const parts = [regex];
const posParams: { [key: string]: UrlSegment } = {};
const consumed: UrlSegment[] = [];
let currentIndex = 0;
for (let i = 0; i < parts.length; ++i) {
if (currentIndex >= segments.length) {
return null;
}
const current = segments[currentIndex];
const part = parts[i];
if (!part.test(current.path)) {
return null;
}
posParams[paramName] = current;
consumed.push(current);
currentIndex++;
}
if (route.pathMatch === 'full' &&
(segmentGroup.hasChildren() || currentIndex < segments.length)) {
return null;
}
return { consumed, posParams };
}
}
How to use,
/**
* Copyright (c) Matan Shukry
* All rights reserved.
*/
export const UserRoutes: Routes = [
{
path: 'users',
component: UserComponent,
children: [
{
path: '',
component: UserListComponent
},
{
matcher: ComplexUrlMatcher("id", /[0-9]+/),
component: UserItemComponent
},
]
}
];
@NgModule({
imports: [RouterModule.forChild(UserRoutes)],
exports: [RouterModule]
})
export class UserRoutingModule { }