2017-09-26 224 views
-1

如何使用嘗試使用這些類型的網與prefix/foo-bar-1123prefix/foo-bar-1123/bazquux-123與Angular 4路由器?重要的部分是我試圖捕獲的數字ID。使用URL中的路由器參數與角4路由器

我試過這個,但結果是,我得到了/ /字符捕獲到單個變量稱爲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 

這是不是該路由器支持?是否可以擴展路由器來支持這些?

回答

0

創建一個自定義的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, 
    } 
]