2016-07-28 68 views
0

继承人我的路由器配置:使用儿童角2路由器指出抛出错误

import { RouterConfig } from '@angular/router'; 

... 

export const AppRoutes : RouterConfig = [ 
    { 
    path: '', 
    redirectTo: 'myview', 
    pathMatch: 'full' 
    }, 
    { 
    path: 'myview', 
    component: ViewComponent, 
    children: [{ 
     path: 'hello', 
     component: HelloComponent 
    }] 
    }, 
]; 

当我尝试加载页面我收到以下错误:

EXCEPTION: Error: Uncaught (in promise): Error: Cannot match any routes: '' 

然而,当我做孩子路线的兄弟姐妹,像这样:

export const AppRoutes : RouterConfig = [ 
    { 
    path: '', 
    redirectTo: 'myview', 
    pathMatch: 'full' 
    }, 
    { 
    path: 'myview', 
    component: ViewComponent 
    }, 
    { 
     path: 'hello', 
     component: HelloComponent 
    } 
]; 

我能够正常加载页面没有任何错误。我究竟做错了什么?

回答

1

因为您设计的方式是在初始加载时它已经登陆ViewComponent组件,但ViewComponent有孩子,所以必须重定向到内部组件。

您需要为儿童添加一条路线routes,这会将''重定向到hello组件。

export const AppRoutes: RouterConfig = [ 
    { path: '', redirectTo: 'myview', pathMatch: 'full'}, 
    { path: 'myview', component: ViewComponent, 
     children: [ 
     { path: '', pathMatch: 'full', redirectTo: 'hello' }, //added redirection to hello 
     { path: 'hello', component: HelloComponent } 
    ] 
    } 
]; 

Note: Make sure you have <router-outlet></router-outlet> in myview component HTML so that child route view can be shown correctly.

+0

为什么第一个孩子的路径设置为空字符串?这使得我的应用程序自动从页面根重定向到'HelloComponent'。 – dopatraman

+0

你想怎么做呢? –

+0

我在home组件中有一个链接,它将我发送给'ViewComponent'。然后我在'ViewComponent'中有一个连接到'HelloComponent'。 – dopatraman

0

你不使用你的RouterConfig ''任何路线。

由于重定向后新路径将为https://yourdomain/myview/。为此,您只创建了https://yourdomain/myview/hello route in routeCofig

我已经创建了角度为2的应用程序。您可以在Github上查看源代码here

只需添加下面一行到你的孩子路径列:

{path: '', component: HelloComponent }

检查hero.routes.tsdragon.routes.ts文件,他们会帮助你更清楚地了解路由。希望它会有所帮助。谢谢。