如何在 Angular 2 中定义嵌套的子路由?

How do I define nested child routes in Angular 2?

我的app结构如下

.
├── photos
├── posts
├── users
│   ├── detail
│   │   ├── address
│   │   ├── family
│   │   ├── information
│   │   └── phones
│   ├── friends
│   └── profile
└── videos

要创建嵌套路由,我更喜欢在自己的级别上使用相同级别的路由。

例如:

一级路由进入根路由。二级路由到用户路由,三级路由到详细路由。

所以根路由看起来像这样,

const appRoutes: Routes = [
  {
    path: '',
    component: HomeComponent
  },
  {
    path: 'photos',
    component: PhotosComponent
  },
  {
    path: 'posts',
    component: PostsComponent
  },
  {
    path: 'users',
    component: UserListComponent
  },
  {
    path: 'user/:username',
    component: UserComponent
  },
  {
    path: 'videos',
    component: VideosComponent
  }
]
export const AppRoutes = RouterModule.forRoot(appRoutes);


// and the for the user routes,


const userRoutes: Routes = [
  {
    path: 'detail',
    component: DetailComponent
  },
  {
    path: 'friends',
    component: FriendsComponent
  },
  {
    path: 'profile',
    component: ProfileComponent
  }
]
export const UserRoutes = RouterModule.forChild(userRoutes);

// and for the detail routes,


const detailRoutes: Routes = [
  {
    path: 'address',
    component: AddressComponent
  },
  {
    path: 'family',
    component: FamilyComponent
  },
  {
    path: 'info',
    component: InformationComponent
  },
  {
    path: 'phones',
    component: PhonesComponent
  }
]
export const DetailRoutes = RouterModule.forChild(detailRoutes);

如何混淆给定的路线? 我希望路由是 /users/:username/detail/info 但不知道如何将它们耦合。

您必须使用 children 属性设置每条路线的子路线。如果您想将它们保存在单独的文件中,我想您可以导出 Routes 的 const 数组(而不是 RouterModule)并导入它们以便通过执行以下操作来使用它们:

user.routes

export const userRoutes : Routes = [
  {
    path: 'detail',
    component: DetailComponent
  },
  {
    path: 'friends',
    component: FriendsComponent
  },
  {
    path: 'profile',
    component: ProfileComponent
  }
]

app.routes

import {userRoutes} from './user/user.routes'

const appRoutes: Routes = [
  {
    path: '',
    component: HomeComponent
  },
  {
    path: 'photos',
    component: PhotosComponent
  },
  {
    path: 'posts',
    component: PostsComponent
  },
  {
    path: 'users',
    component: UserListComponent
  },
  {
    path: 'user/:username',
    component: UserComponent,
    children: [userRoutes[0]]
  },
  {
    path: 'videos',
    component: VideosComponent
  }
]
export const AppRoutes = RouterModule.forRoot(appRoutes);