Angular 6 - 带前缀的动态路由

2024-01-01

我正在开发 Angular 通用应用程序。我想创建带有自定义前缀的动态路由,但我找不到与我的案例相关的任何有用的文档。任何帮助将不胜感激...

Details:

我所拥有的是,我有 4 个页面,其中有 4 个不同的动态 URL,它们是:

  • 主页 (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})

我做了什么

我已经注册了一个路由来处理主页、类别和子类别页面,因为它们具有相同的 UI 和下面提到的动态类别级别,

RouterModule.forRoot([
      {path: '**', component: HomeComponent, data: {title: 'Home', description: 'Homepage - quick overview.'}}
    ])

挣扎:

现在,我无法添加产品和用户页面的路由,我无法理解如何添加p and user斜杠之后和之前的前缀ids分别在产品页面和用户页面中。如果没有这些前缀,路由就可以正常工作。

产品和用户页面所需 URL 的示例

  • 产品页面(http://example.com/p123-产品名称 http://example.com/p123-Product-Name)
  • 用户页面(http://example.com/user123-用户名 http://example.com/user123-User-Name)

我在用@angular/router用于路由。

提前致谢。


谢谢@Yuriy 重新打开这个,我已经从@Ingo Bürk 的评论中得到了答案。 下面提到的Gist帮助我通过正则表达式创建路线。https://gist.github.com/matanshukry/22fae5dba9c307baf0f364a9c9f7c115 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 { }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular 6 - 带前缀的动态路由 的相关文章

随机推荐