我有嵌套路线。
@Routes([
{ path: "/", component: RootComponent },
{ path: "/parent", component: ParentComponent }])
二级路线有参数。
@Routes([
{ path: "/:id", component: ChildComponent },
{ path: "/child/:id", component: ChildComponent }]) //same component
当我使用RouterLink导航时:
['/parent/child/1']
我收到错误:
组件'ChildComponent'没有路由配置。
如果我将嵌套路线更改为一个级别(平坦)路线:
@Routes([
{ path: "/", component: RootComponent },
{ path: "/parent", component: ParentComponent },
{ path: "/child/:id", component: ChildComponent }])
比一切正常(RouterLink相同)。
问题:我的错误在哪里?
更新:当我只使用一个简单的网址时,嵌套路由也不起作用:例如
http://server/parent/child/1
网址
答案 0 :(得分:4)
<强>问题:强>
此错误消息的原因是,使用新的Angular 2 RC1路由时,您实际上是在构建路由树,因此当您要求'/parent/child/1'
时,您的第二个最后路由段(/child/
)会将您发送到ChildComponent和angular查看ChildComponent以查看是否有任何路由可以匹配到下一个句段(/1
),并且由于您没有在ChildComponent中定义任何路由,因此会抛出此异常:
Cannot match any routes. Current segment: '1'. Available routes: [].
解决方案:
像你一样在AppComponent中定义你的(平面)路径树绝对是解决这个问题的一种方法。另一种方法是通过将ParentComponent中的路由更改为:
来区分您的第二级路由@Routes([
{ path: 'childs', component: ChildComponent },
{ path: 'child/:id', component: ChildComponent },
])
基本上我们创建两个分支childs
和child/:id
都路由到ChildComponent。
为什么定义childs
路线有效?
基本上Angular 2 RC1路由器在定义了名为child/:id
的路由时,不处理child
路由作为一个整体,相反,角度路由器断开child/:id
路由到child
和:id
的两个路由段,然后使用child
路由的定义将您带到ChildComponent,然后查找:id
的路由定义在ChildComponent中找不到任何段。通过将child
路由重命名为childs
,我们强制角度将child/:id
作为一个整体,并将我们带到ChildComponent作为我们想要的最终目的地。
深层链接
关于深层链接的第二个问题:
当我只使用一个简单的url时,嵌套路由也不起作用: 例如http://server/parent/child/1
假设您使用默认的PathLocationStrategy
作为您的LocationStrategy,您需要确保您的Web服务器为每个路径路径提供index.html
文件。例如,在实时服务器中,我将以下参数添加到Web服务器启动命令:
live-server --entry-file=index.html
<强>更新强> 看起来这是known bug in RC1并且更改路由的顺序使一切正常工作。请参阅David的答案。
答案 1 :(得分:3)
@Routes([
{ path: "/child/:id", component: ChildComponent },
{ path: "/:id", component: ChildComponent }]) //same component
它有效,但不知道为什么。
我确定这些是网址映射:
http://localhost/parent/1
- &gt;选择第二个配置http://localhost/parent/child/1
- &gt;选择第一个配置<强>更新强>
正如它出现的那样,现在已知问题:https://github.com/angular/angular/issues/8420
答案 2 :(得分:0)
定义路线时,您可以通过添加此语法&#34; /..."来定义路线未终止。
对于您的父路线,您应该这样写:
父母的组件:
import {TestComponent} from '';
@Routes([
{ path: "/", component: RootComponent },
{ path: "/parent/...", name: 'Parent', component: TestComponent }
])
名为TestComponent的儿童组件:
@Routes([
{path: '/:id', name: 'Id', component: ChildComponent },
{path: '/child/:id', name: 'ChildId', component: ChildComponent }
])