首页 > 解决方案 > Angular 6 - Dynamic Routing with Prefix

问题描述

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:

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.

标签: angularangular-routerangular6dynamic-url

解决方案


谢谢@Yuriy 重新打开这个,我已经从@Ingo Bürk 的评论中得到了答案。下面提到的Gist帮助我通过正则表达式创建路由。 https://gist.github.com/matanshukry/22fae5dba9c307baf0f364a9c9f7c115

作为参考,我在下面添加了源代码,

/**
 * 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 };
    }
}

如何使用,

/**
 * 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 { }

推荐阅读