Javascript 在URL中使用路由器参数与Angular 4路由器
如何在Angular 4路由器上使用前缀为Javascript 在URL中使用路由器参数与Angular 4路由器,javascript,angular,angular4-router,Javascript,Angular,Angular4 Router,如何在Angular 4路由器上使用前缀为prefix/foo-bar-1123、前缀为prefix/foo-bar-1123/bazzux-123的此类URL?重要的是我试图捕捉的数字id 我已经尝试过了,但结果是我得到了一个//characterized之间的所有数据,并捕获到一个名为categorySlug-:categoryId和subcategorySlug-:subcategoryId的变量 const routes = [{ path: 'prefix/:categorySlu
prefix/foo-bar-1123
、前缀为prefix/foo-bar-1123/bazzux-123
的此类URL?重要的是我试图捕捉的数字id
我已经尝试过了,但结果是我得到了一个//characterized之间的所有数据,并捕获到一个名为categorySlug-:categoryId
和subcategorySlug-: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
这是路由器支持的吗?是否可以扩展路由器以支持这些功能?创建一个自定义UrlMatcher,可用于实现匹配并从URL获取id。这至少在第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,
}
]