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

时间:2017-03-15 09:06:22

标签: angular typescript angular2-routing

我的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,但无法弄清楚如何将它们联系起来。

1 个答案:

答案 0 :(得分:0)

您必须使用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);