角形路径中的复杂正则表达式

时间:2019-06-06 17:45:04

标签: angular angular-ui-router

我们正在将我们的网站从YII2迁移到AngularJS(6.1)。在YII2中,我们对某些URL使用正则表达式 像:-

 s/<content:[\w\ ,.]+>-wholesale-supplier-in-<country:\w+>

因此我们在app-routing.module.ts文件中添加了此正则表达式

我们试图在app-routing.module.ts文件中添加相同的正则表达式,因为我们不想更改我们的URL。因此,我们将此代码添加到了角路线文件

const routes: Routes = 
      [{
         path:'s/:searchstring-wholesale-supplier-in-:country',
         component:SearchdataComponent
    }}

我们也尝试过

     const routes: Routes = 
      [{
         regex:'s/<searchstring:[\w\ ,.]+>-wholesale-supplier-in-<country:\w+>',
         path:'s/:searchstring-wholesale-supplier-in-:country',
         component:SearchdataComponent
    }}

但是当我们使用这种类型的正则表达式时,它会显示

Cannot match any routes. URL Segment: 's/apple-wholesale-supplier-in-canada'

使用第二个代码,我们将无法访问任何参数。

我们如何才能实现相同的URL路由?

1 个答案:

答案 0 :(得分:0)

我认为您可以编写自定义匹配器。我在这里使用您的正则表达式,但尚未对其进行测试,但是您会相信它是可行的,像这样定义匹配器:

function customMatcher(url: UrlSegment[]) {
  let re = /<content:[\w\ ,.]+>-wholesale-supplier-in-<country:\w+>/;
  return url.length === 2 && url[0].path === 's' && re.test(url[1].path) ? ({consumed: url}) : null;
}

然后定义您的路线:

{
     matcher: customMatcher,
     component:SearchdataComponent
}

这未经测试,但应该具有理想的匹配结果。但是您仍然必须自行解析参数。