typescript - 在 Angular2 组件路由中,带有子路由的导航栏中路径名称重复
我在将组件路由集成到我的 Angular2 应用时遇到了一些问题,因为当我尝试在应用中导航时,会出现以下错误:'EXCEPTION: Error: Uncaught (in promise): Error: Cannot match any routes:'
因此,在参考了 Stackoverflow 和官方文档的一些建议后,我在 Routes 中对子路由应用了一个重定向对象,如下所示
children: [
{
path: ':id',
component: DetailMoreLayout
},
{
path: '',
redirectTo: 'parent-path',
pathMatch: 'full'
}
]
所以在我的应用程序中,我有以下路由。请注意,DisplayRoutes 是我通过扩展 Route 对象创建的自定义类型:
export const routes:DisplayRoutes = [
{
path: '',
display: 'Home',
component: HomeComponent
}, {
path: 'about-us',
display: 'About Us',
component: LeftSubNavigation,
index: {
component: DetailMoreLayout
},
children: [
{
path: ':id',
component: DetailMoreLayout
},
{
path: '',
redirectTo: 'about-us',
pathMatch: 'full'
}
]
}, {
path: 'teams',
display: 'Teams',
component: LeftSubNavigation,
index: {
component: DetailMoreLayout
},
children: [
{
path: ':id',
component: DetailMoreLayout
},
{
path: '',
redirectTo: 'teams',
pathMatch: 'full'
}
]
}, {
path: 'careers',
display: 'Careers',
component: LeftSubNavigation,
index: {
component: DetailMoreLayout
},
children: [
{
path: ':id',
component: DetailMoreLayout
},
{
path: '',
redirectTo: 'careers',
pathMatch: 'full'
}
]
}, {
path: 'press',
display: 'Presse',
component: LeftSubNavigation,
index: {
component: DetailBlogLayout
},
children: [
{
path: ':id',
component: DetailBlogLayout
},
{
path: '',
redirectTo: 'press',
pathMatch: 'full'
}
]
}, {
path: 'technology',
display: 'Technology',
component: LeftSubNavigation,
index: {
component: DetailBlogLayout
},
children: [
{
path: ':id',
component: DetailBlogLayout
},
{
path: '',
redirectTo: 'technology',
pathMatch: 'full'
}
]
}, {
path: 'promotion',
display: 'Promotion',
component: LessLayout
}, {
path: 'contact',
display: 'Contact',
component: LeftSubNavigation,
index: {
component: DetailMoreLayout
},
children: [
{
path: ':id',
component: DetailMoreLayout
},
{
path: '',
redirectTo: 'contact',
pathMatch: 'full'
}
]
}
];
现在一切都没问题了,但我应该在 HTML 模板中使用 routerLink 指令来链接路由,还是在组件中使用 .navigateByUrl(route) 或 .navigate([route]) 方法?我的 URL/路径被重复了,所以 http://localhost:4200/about-us/ 变成了 http://localhost:4200/about-us/about-us。即使直接访问或“深度链接”到 http://localhost:4200/about-us,浏览器中的 URL 也会被更改为 http://localhost:4200/about-us/about-us
我哪里做错了?有人能看到吗?我尝试将 pathMatch: 'full' 设置为 pathMatch: 'prefix',但这不起作用。我使用的是 "@angular/router": "3.0.0-beta.2"
答案#1
不完全确定,因为我还没有在新的路由器上做很多尝试,但我怀疑你应该把重定向改为 redirectTo: '../about-us'。这样它会导航到父 router 并在那里查找 about-us 路径:
export const routes:DisplayRoutes = [
{
path: '',
display: 'Home',
component: HomeComponent
}, {
path: 'about-us',
display: 'About Us',
component: LeftSubNavigation,
index: {
component: DetailMoreLayout
},
children: [
{
path: ':id',
component: DetailMoreLayout
},
{
path: '',
redirectTo: '../about-us', //<-- here
pathMatch: 'full'
}
]
},
...
]
答案#2
我认为你在你的应用程序中实现了经典的主从模式,它是无组件路由的完美使用案例。
你需要重构你的父模板,以使用左右两个 router-outlet 并在那里加载。
看看这篇优秀的文章
旁注:您的应用程序当前的行为与配置一致。
当您在地址栏输入 /about-us 时,它会查找 '' 路由,该路由又指向 about-us,因此它会再次添加 about-us。
