首页 > 解决方案 > Angular 4默认子路由不起作用

问题描述

我有具有以下结构的 angular 4 项目:

src
|- app
|  |- home
|  |  |- home.component.ts/html/scss
|  |  |- home.module.ts
|  |  |- home.routing.ts
|  |  |- products
|  |  |  |- products.component.ts/html/scss
|- app.component.ts/html/scss
|- app-routing.module.ts
|- app.module.ts

我的app.routing.module.ts文件包含以下内容:

const routes: Route[] = [
{
    path: "home", component: HomeComponent, canActivate: [AppAuthGuard]
  },
  {
    path: '', redirectTo: AppConstants.ROUTE_LOGIN, pathMatch: 'full'
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes, {useHash: false})],
  exports: [RouterModule]
})

export class AppRoutingModule {
}

home.routing.ts包含以下子路由:

{
path: "home",
component: HomeComponent,
children: [
  {
    path: '',
    pathMatch: 'full',
    component: HomeStatsComponent
  },
  {
    path: 'products',
    children: [
      {
        path: '',
        pathMatch: 'full',
        component: ProductsComponent
      }
      {
        path: 'add',
        component: AddProductComponent
      }
    ]
  },
 ]
}

在 home.module.ts 中,子路由已使用RouterModule.forChild(HomeRoutes). 在 home.component.html 中有一个子路由的路由器出口。除了默认子路由 ( http://localhost:4200/home) 之外的所有路由都成功运行(http://localhost:4200/home/products运行正常)。http://localhost:4200/home没有错误,它只是显示空白区域,因为路由器出口是空的。但是,如果我在其中定义主组件的默认子路由,app.module.ts它就可以正常工作。我做错了什么让它不起作用?

标签: angularangular-routingangular4-router

解决方案


能不能直接去掉一级配置试试。由于您已经将它路由到home,它正在路由中找到/home/home因此根据配置它成为http://localhost:4200/home/home

 [ 
   {
    path: '',
    pathMatch: 'full',
    component: HomeStatsComponent
  },
  {
    path: 'products',
    children: [
      {
        path: '',
        pathMatch: 'full',
        component: ProductsComponent
      }
      {
        path: 'add',
        component: AddProductComponent
      }
    ]
  }
]

推荐阅读