Angular 5 子路由向路由添加括号 [英] Angular 5 child routes adding parentheses to the route
问题描述
我有一个包含一系列组件的 Angular 5 应用程序.有些组件是其他组件的子组件,有些则不是.
I have an Angular 5 application with a series of components. Some of the components are children of others, and some are not.
我希望应用程序具有如下结构:
I would like the application to have a structure such as:
*/my-account/overview // homepage
*/my-account/my-stuff
*/profile
*/non-default
我有一个 DefaultComponent,其中包含一些通用元素,例如我希望在大多数页面上出现的站点导航(除 */非默认路由/组件外的所有内容).
I have a DefaultComponent that contains some generic elements such as site navigation that I would like to be present on most of the pages (everything except for the */non-default route/component).
我的路由模块定义了以下路由:
My routing module defines the routes below:
export const routes: Routes = [
{ path: '', redirectTo: 'my-account', pathMatch: 'full' }, // should redirect to localhost:4200/my-account
{ path: '', component: DefaultComponent, children: [
{ path: 'my-account', children: [
{ path: '', redirectTo: 'overview', pathMatch: 'full' }, // should redirect to localhost:4200/my-account/overview
{ path: 'overview', component: OverviewComponent }, // should resolve: localhost:4200/my-account/overview
{ path: 'my-stuff', component: MyStuffComponent } // should resolve: localhost:4200/my-account/my-stuff
]},
{ path: 'profile', component: ProfileComponent } // should resolve: localhost:4200/profile
]},
{ path: 'non-default', component: NonDefaultComponent } // should resolve: localhost:4200/non-default
];
如果我直接在浏览器中点击 URL,这些路由可以完美解析.我遇到的问题是,当我尝试使用 [routerLink] 指令呈现锚点时,实际应用于 href 的 URL 是
These routes resolve perfectly if I hit the URL directly in the browser. The problem I have is that when I try to render an anchor with a [routerLink] directive, the URL that is actually applied to the href is
href="/my-account/overview/(profile)"
href="/my-account/overview/(profile)"
而不是
href="/profile"
href="/profile"
用于 ProfileComponent.因此,如果我使用 [routerLink] 呈现导航项列表,则每个项都有一个实际上未解析为组件的 href.
for the ProfileComponent. So if I render a list of navigation items with [routerLink], each of the items has an href that doesn't actually resolve to the component.
如果有帮助,我有一个 Github 存储库在这里演示该问题.
If it helps, I have a Github repository demonstrating the issue here.
我是否错误地配置了路由?
Have I misconfigured the routing?
推荐答案
正如 Eliseo 正确指出的那样.我在 RouterLink 本身的路由开始处遗漏了一个斜线.
As Eliseo correctly pointed out. I was missing a slash at the beginning of my routes in the RouterLink itself.
[routerLink]=['my-account/overview']
[routerLink]=['my-account/overview']
应该是
[routerLink]=['/my-account/overview']
[routerLink]=['/my-account/overview']
值得注意的是,在我引入子路由之前,它一直运行良好.
It's worth noting that it had been working fine until I introduced child routes.
这篇关于Angular 5 子路由向路由添加括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!