如何在Angular2中使用:id参数创建子路由

时间:2016-10-27 15:39:40

标签: angular angular2-routing

我有以下routeConfig,这条路线正常工作:

export const routeConfig: Routes = [
    {path: '', redirectTo: 'use-cases', pathMatch: 'full'},
    {path: 'use-cases', component: UseCasesComponent},
    {path: 'add', component: AddComponent},
    {path: '**', redirectTo: 'use-cases'},
];

如何为use-cases/:id添加路线?

我试过这个:

{path: 'use-cases', component: UseCasesComponent,
    children: [
        {
            path: '/:id',
            component: UseCaseComponent,
        }
    ]
},

但它给了我错误

异常:未捕获(承诺):[object Object]

Error: Uncaught (in promise): [object Object]
    at resolvePromise (http://localhost:3000/polyfills.bundle.js:15073:32)
    at http://localhost:3000/polyfills.bundle.js:15050:14
    at ZoneDelegate.invoke (http://localhost:3000/polyfills.bundle.js:14837:27)
    at Object.onInvoke (http://localhost:3000/vendor.bundle.js:7133:42)
    at ZoneDelegate.invoke (http://localhost:3000/polyfills.bundle.js:14836:33)
    at Zone.run (http://localhost:3000/polyfills.bundle.js:14719:44)
    at http://localhost:3000/polyfills.bundle.js:15107:58
    at ZoneDelegate.invokeTask (http://localhost:3000/polyfills.bundle.js:14870:36)

3 个答案:

答案 0 :(得分:2)

不要向path: '...'

添加前导斜杠
 path: '/:id'

应该是

 path: ':id'

答案 1 :(得分:0)

试试这个:

{
    path: 'use-cases', component: UseCasesComponent,
    children: [
        {
            path: ':id',
            component: UseCaseComponent,
        }
    ]
},

有效!

答案 2 :(得分:0)

试试这个,在第一条路径中添加孩子

export const routeConfig: Routes = [
   {path: '', redirectTo: 'use-cases', pathMatch: 'full', children:   [{path: ':id', component: UseCaseComponent}]},
   {path: 'use-cases', component: UseCasesComponent},
   {path: 'add', component: AddComponent},
   {path: '**', redirectTo: 'use-cases'},
];

我希望有所帮助。