Angular 2路由:伟大的孙子

时间:2016-10-05 17:28:50

标签: angular angular2-routing

在嵌套子路由时,我遇到了我的曾孙路线上的cannot match any routes错误。

前往儿童的路线:

const appRoutes = [
  {
    path: '',
    redirectTo: '/one',
    pathMatch: 'full',
  },
  {
    path: 'one',
    component: OneComponent,
  },
  {
    path: 'two',
    component: TwoComponent,
  },
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

前往孙子的路线:

const oneRoutes: Routes = [
  {
    path: 'one',
    component: OneComponent,
    children: [
      {
        path: '',
        redirectTo: 'a',
        pathMatch: 'full',
      },
       { path: 'a', component: AComponent },
       { path: 'b', component: BComponent },
    ],
  },
];
export const oneRouting: ModuleWithProviders = RouterModule.forChild(oneRoutes);

给曾孙子的路线:

const aRoutes: Routes = [
  {
    path: 'a',
    component: AComponent,
    children: [
      {
        path: '',
        redirectTo: 'sub-one',
        pathMatch: 'full',
      },
       { path: 'sub-one', component: SubOneComponent },
       { path: 'sub-two', component: SubTwoComponent },
    ],
  },
];

export const aRouting: ModuleWithProviders = RouterModule.forChild(aRoutes);

孩子OneModule正在导入AModuleoneRouting

@NgModule({
  imports: [ CommonModule, oneRouting, AModule ],
  declarations: [ OneComponent, BComponent ],
  exports: [ OneComponent ]
})
export class OneModule {}

和孙子AModule正在导入aRouting

@NgModule({
  imports: [ CommonModule, aRouting ],
  declarations: [ AComponent, SubOneComponent, SubTwoComponent ],
  exports: [ AComponent ]
})
export class AModule {}

一个有趣的事情我注意到:当应用程序启动时,它导航到默认子路由one,但不导航到孙路由a。如果我导航到路由two然后返回one,它会找到默认路由a

为什么Angular2不会看到那些伟大的孙子路线?

http://localhost:3000

修改

如果我将所有孙子路由组合到一个路由器中,则路由工作正常:

const oneRoutes: Routes = [
  {
    path: 'one',
    component: OneComponent,
    children: [
      {
        path: '',
        redirectTo: 'a',
        pathMatch: 'full',
      },
       { 
         path: 'a', 
         component: AComponent, 
         children: [
            {
              path: '',
              redirectTo: 'sub-one',
              pathMatch: 'full',
            },
             { path: 'sub-one', component: SubOneComponent },
             { path: 'sub-two', component: SubTwoComponent },

           ],
       },
       { path: 'b', component: BComponent },
    ],
  },
];

link to plunk...

所以我想要确定的是,我们是否仅限于将这些子路由模块放在主要模块之外,或者如果我的初始实现已关闭。

更新

正如Robin建议的那样,使用延迟加载模式允许嵌套路由。 revised plunk感兴趣的任何人。

0 个答案:

没有答案