Skip to content

Instantly share code, notes, and snippets.

@shengoo
Last active November 4, 2016 08:38
Show Gist options
  • Save shengoo/b1c058e94f24a3e73e6dbd9faf7fc791 to your computer and use it in GitHub Desktop.
Save shengoo/b1c058e94f24a3e73e6dbd9faf7fc791 to your computer and use it in GitHub Desktop.
angular2 nested routes

## angular2里的路由模块支持多层嵌套路由,不需要像angular1那样使用第三方的路由了。

具体配置如下:

const routes: Routes = [
  {path: '', component: IndexComponent},
  {path: 'home', component: HomeComponent},
  {path: 'about', component: AboutComponent  }//redirectTo: 'about/about1'
];

const aboutRoutes: Routes = [
  {
    path: 'about',
    component: AboutComponent,
    children: [
      {
        path: '',
        children: [
          {
            path: 'about1',
            component: About1Component
          },
          {
            path: 'about2',
            component: About2Component
          }
        ]
      }
    ]
  }
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes),
    RouterModule.forChild(aboutRoutes)
  ],
  exports: [RouterModule]
})

这段代码配置了两个跟路由和about路由下的两个子路由。

RouterModule

RouterModule提供了两个函数:

  • forRoot creates a module that contains all the directives, the given routes, and the router service itself.
  • forChild creates a module that contains all the directives and the given routes, but does not include the router service.

注册根路由的时候,这样:

@NgModule({
  imports: [RouterModule.forRoot(ROUTES)]
})
class MyNgModule {}

submodules 和 and lazy loaded submodules 这样注册:

@NgModule({
  imports: [RouterModule.forChild(ROUTES)]
})
class MyNgModule {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment