【问题标题】:Using Router Parameters in URLs with Angular 4 Router在 Angular 4 路由器的 URL 中使用路由器参数
【发布时间】:2017-09-26 10:45:23
【问题描述】:

如何尝试将这些 URL 与 prefix/foo-bar-1123prefix/foo-bar-1123/bazquux-123 与 Angular 4 路由器一起使用?重要的位是我试图捕获的数字 id。

我已经尝试过了,但结果是我得到了 // characted 之间的所有数据,这些数据被捕获到名为 categorySlug-:categoryIdsubcategorySlug-:subcategoryId 的单个变量中。

const routes = [{
  path: 'prefix/:categorySlug-:categoryId',
  component: MyComponent,
}, {
  path: 'prefix/:categorySlug-:categoryId/:subcategorySlug-:subcategoryId',
  component: MyComponent,
}]

export const MyRoute: ModuleWithProviders = RouterModule.forChild(routes)

最终我想得到这些变量:

categorySlug=foo-bar
categoryId=1123
subcategorySlug=bazquux
subcategoryId=123

这是路由器支持的东西吗?是否可以扩展路由器以支持这些?

【问题讨论】:

    标签: javascript angular angular4-router


    【解决方案1】:

    创建一个自定义的 UrlMatcher,可用于实现匹配并从 URL 获取 id。这至少在 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,
      }
    ]
    

    【讨论】:

      猜你喜欢
      • 2018-05-01
      • 1970-01-01
      • 2016-07-17
      • 2019-04-17
      • 1970-01-01
      • 2018-07-28
      • 1970-01-01
      • 2018-02-05
      • 1970-01-01
      相关资源
      最近更新 更多