【问题标题】:Angular child route loading parent instead of child componentAngular子路由加载父组件而不是子组件
【发布时间】:2019-05-06 14:48:36
【问题描述】:

我正在尝试根据父子概念导航我的 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 }
];

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

请帮忙解决这个问题。

【问题讨论】:

  • 它没有重定向到SolutionComponent。它按预期工作。按照您配置路由的方式,SolutionComponent 在 HTML 中应该有一个 <router-outlet>。然后,如果您导航到solutions/cog,它将显示SolutionComponentCogComponent 代替router-outlet

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


【解决方案1】:
...
{
    path: 'solutions', component: SolutionComponent,
    children: [
        { path: 'cog', component: CogComponent }
    ]
},
...

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

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

上述路线应该可以按您的预期工作。

【讨论】:

  • 有没有办法避免这种情况?我需要让我的父母和孩子使用组件,但我也将我的路由数据用于面包屑。所以我需要让孩子在我父母的孩子中,并为父母提供一个组件
【解决方案2】:

您的第二种方法有效,因为 Angular 将在父路由器插座本身中加载 CogComponent 模板。如果这是您想要的,那么您最好采用这种方法。

但是,如果您想让SolutionComponent 作为CogComponent 的父级,那么您必须将<router-outlet></router-outlet> 添加到solution.component.html

方法如下:

...

<router-outlet></router-outlet>

这将告诉 Angular 它需要在那里加载CogComponent,因为/cog/solution 路由的子路由。


这里有一个Working Sample StackBlitz 供您参考。

【讨论】:

    猜你喜欢
    • 2017-11-20
    • 1970-01-01
    • 2018-10-31
    • 2016-12-19
    • 2021-05-31
    • 2019-12-02
    • 2018-03-24
    • 1970-01-01
    • 2018-03-09
    相关资源
    最近更新 更多