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

标签 angular typescript angular2-routing

我的应用结构如下

.
├── 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 的常量数组(而不是 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);

关于angular - 如何在 Angular 2 中定义嵌套的子路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42805263/

相关文章:

angular - 为什么在构造函数中初始化的成员变量在 ionic/angular 的 ngInit 中未定义?

javascript - 无法使用 ng-packagr 获取已发布的包

typescript - 定义类型以从类型的选定键中创建对象似乎已被破坏

javascript - 使用 if else 更改 Power BI 自定义视觉对象的矩形颜色

javascript - Angular - 从多个订阅中获取一个订阅

javascript - 用输入字段 Javascript/Angular2 替换某些单词

javascript - 使用 T 的参数类型 U 获取类型 T 函数的参数类型

angular - 如何在 Angular 2 中动态加载和显示包含 routerLink 指令的 html?

angular - 如何 router.navigate 到路由 url 中带有 id 占位符的路由

Angular 2 动态页面页眉和页脚