角子级路由不会自己加载并且加载父组件

时间:2018-12-05 05:00:12

标签: angular angular-ui-router angular4-router

我试图基于父子概念导航我的Angular应用程序。 在加载时,父组件而不是子组件将被加载,但url似乎是

const appRoute: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'dashboard', component: DashboardComponent },
  {
    path: 'solutions', component: SolutionComponent,
    children: [
      { path: 'cog', component: CogComponent }
    ]
  },
  { path: 'portfolio', component: PortfolioComponent },
  { path: '**', component: PortfolioComponent }
];

当我运行solutions/cog时,它会重定向到SolutionComponent,但它应该加载CogComponent

编辑:1

在我使用

时可以使用
const appRoute: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'dashboard', component: DashboardComponent },
  { path: 'solutions', component: SolutionComponent },
  { path: 'solutions/cog', component: CogComponent },
  { path: 'portfolio', component: PortfolioComponent },
  { path: '**', component: PortfolioComponent }
];

但是我希望它应该从上述方法加载。

请帮助解决此问题。

2 个答案:

答案 0 :(得分:1)

...
{
    path: 'solutions', component: SolutionComponent,
    children: [
        { path: 'cog', component: CogComponent }
    ]
},
...

由于您为路径component声明了solutions,因此它显示了SolutionComponent,它将在嵌套的CogComponent中呈现router-outlet

{ path: 'dashboard', component: DashboardComponent },
{
    path: 'solutions'
    children: [
        { path: 'cog', component: CogComponent },
        { path: '', component: SolutionComponent, pathMatch: 'full'}
    ]
},
...

上述路线应能按预期工作。

答案 1 :(得分:0)

您的第二方法可以正常工作,因为Angular会将CogComponent模板加载到父路由器出口本身中。如果那是您想要的,那么最好采用这种方法。

但是,如果您想将SolutionComponent作为CogComponent的父项,则必须在<router-outlet></router-outlet>上添加solution.component.html

方法如下:

...

<router-outlet></router-outlet>

这将告诉Angular,由于CogComponent/cog路由的子路由,因此需要在其中加载/solution


这是您推荐的Working Sample StackBlitz