繁体   English   中英

在Angular 2路由器中使用子状态会引发错误

[英]Using children states in Angular 2 router throws error

这是我的路由器配置:

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
    }
];

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

因为您的设计方式是在初始负载下进行的,所以它会降落在ViewComponent组件上,但是ViewComponent有子组件,因此必须重定向到内部组件。

您需要再向子级routes添加一条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 }
    ]
  }
];

注意:确保myview组件HTML中具有<router-outlet></router-outlet> ,以便可以正确显示子路由视图。

您在RouterConfig中没有为''使用任何路由。

重定向后,新路径将为https://yourdomain/myview/ 为此,您仅在https://yourdomain/myview/hello创建了https://yourdomain/myview/hello路由

我已经创建了一个应用程序的角度2.您可以查看源在这里 Github上。

只需将以下行添加到您的子路径数组中:

{path: '', component: HelloComponent }

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM