typescript - 我如何在 Angular 2 中定义嵌套子路由?
我的应用程序结构如下
.
├── 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
你必须使用children属性来设置每个路由的子路由。如果你想将它们保存在不同的文件中,我想你可以导出Routes的常量数组(而不是RouterModule),然后通过类似这样的方式导入使用它们:
用户.路由
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);
