Cannot navigate to child routes using router.navigate method or routerlink :: Error : Cannot match any routes. URL Segment: 'child2'

Cannot navigate to child routes using router.navigate method or routerlink :: Error : Cannot match any routes. URL Segment: 'child2'

这是我的路线常量

const routes: Routes = [
  {
    path: '',
    component: LoginComponent
  },
  {
    path: 'dashboard',
    component: DashboardComponent,
    children: [
      {
        path: '**',
        redirectTo: 'child1'
      },
      {
        path: 'child1',
        component: Child1Component
      },
      {
        path: 'child2',
        component: Child2Component
      }
    ]
  }
];

RouterModule.forRoot(routes)

在模块的导入中添加了这一行。

在 MenuComponent 内部,我尝试使用此行在单击任何菜单(child1 或 child2)时导航到相应的子组件

this.router.navigate(['/dashboard/child1']); //or tried with this.router.navigate(['child1']);

router-outlet 在 DashboardComponent 中

谁能帮我解决这个问题?

这可能是因为 Angular 的第一个匹配策略。当您尝试输入任何 URL 时,通配符是第一个遇到的,并且对所有通配符都是正确的。放到最后就可以了

The order of the routes in the configuration matters and this is by design. The router uses a first-match wins strategy when matching routes, so more specific routes should be placed above less specific routes. In the configuration above, routes with a static path are listed first, followed by an empty path route, that matches the default route. The wildcard route comes last because it matches every URL and should be selected only if no other routes are matched first. Angular Router

{
path: 'dashboard',
component: DashboardComponent,
children: [
  {
    path: 'child1',
    component: Child1Component
  },
  {
    path: 'child2',
    component: Child2Component
  },
  {
    path: '**',
    redirectTo: 'child1'
  }
]

}

父组件将是 DashboardComponent 因为它匹配路由。

为了在 Angular 中有子路由,您必须放置

<router-outlet></router-outlet>

在您的 DashboardComponent 中,这样路由器就会知道在哪里放置 Child1Component。