角度路由:如何在另一个模块中定位子路由

时间:2020-04-29 10:11:21

标签: angular typescript angular-routing

我的主要模块是 app-routing.module ,如下所示:

const ROUTES: Routes = [
  {
    path: 'sport',
    loadChildren: './sport/sport.module#SportModule',
    data: { game: GAME.SPORT }
  }
  {
    path: 'horse-racing',
    loadChildren: './sport/sport.module#SportModule'
    data: { game: GAME.HORSE_RACING }
  }
]

然后在运动模块中,我拥有:

const ROUTES: Routes = [
  {
    path: 'horse-racing',
    component: RacingComponent
  }
  {
    path: '',
    component: SportComponent
  }
]

我基本上希望当用户访问以下内容时

  1. / sport 映射到运动模块中的以下路线:
    {
       path: '',
       component: SportComponent
    }
  1. / horse-racing 映射到运动模块中的以下路线:
    {
       path: 'horse-racing',
       component: RacingComponent
    }

问题:如何配置 app-routing.module 直接加载赛马路线?

2 个答案:

答案 0 :(得分:0)

请尝试这样添加

const ROUTES: Routes = [
  {
    path: 'horse-racing',
    component: RacingComponent
  },
  {
    path: 'sport',
    component: SportComponent
  },
  {
    path: '',
    redirectTo: '/horse-racing',
    pathMatch: 'full',
    runGuardsAndResolvers: 'always'
  }
]

因此,默认情况下,当localhost:4200后有emply字符串时,它将重定向到localhost:4200/horse-racing

答案 1 :(得分:0)

子路由始终会向父路由添加一些内容。这意味着,如果要将SportComponentHorseRacingComponent中的SportModule/sport分组,请将子路由定义为/horse-racing和{{1} }(例如localhost:4200 / horse-racing),根路由必须为空路由。

解决方案

因此,AppRoutingModule中的根路由为:

const appRoutes: Routes = [
  { path: '', loadChildren: './sports/sport.module#SportModule' },
  { path: '**', component: PageNotFoundComponent }
];

以及SportingRouteModule中的子路线:

const sportRoutes: Routes = [
  { 
    path: '', 
    children: [
      { path: 'sport', component: SportComponent },
      { path: 'horse-racing', component: HorseRacingComponent }
    ]
  },
];

检查此Stackblitz以查看其是否有效:https://stackblitz.com/edit/angular-yh5xep

替代

另一方面,您可以将子路由配置为/sport/sport/horse-racing,其中'/ sport'是SportComponent的默认子路由。在这种情况下,可以这样配置根路由:

const appRoutes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'sport', loadChildren: './sports/sport.module#SportModule' },
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: '**', component: PageNotFoundComponent }
];

还有SportRoutingModule中的子路线:

const sportRoutes: Routes = [
  { 
    path: '', 
    children: [
      { path: '', component: SportComponent },
      { path: 'horse-racing', component: HorseRacingComponent }
    ]
  },
];

替代解决方案的演示:https://stackblitz.com/edit/angular-rh8drh