首页 文章

Angular 4嵌套路由器插座

提问于
浏览
2

我在AppComponent中有一个路由器插座,可以很好地加载子组件 . 其中一个子组件有多个子组件,我想将所有子组件加载到父路由器插座中,如下所示

AppComponent  <router-outlet> (This loads all child including products)
  Customers (component)
  Pricing   (component)
  Products  (component) <router-outlet name="products"> (This should load child products)
     TypeProduct1   (Component)
     TypeProduct2   (Component)

但我所有的儿童产品都装在主路由器插座中,例如当我输入网址时

http://localhost:4200/products/typeproduct1 - 它成功加载了TypeProduct1组件,但是在主路由器插座而不是产品路由器插座中 .

我懒洋洋地在路线上装载产品模块 . 这可能是问题吗?

编辑:

路线看起来像这样:

AppRoutingModule:

const routes:Route = [
  { path: 'customers', loadChildren:'/path/to/customers/module' },
  { path: 'pricing', loadChildren:'/path/to/pricing/module' }
  { path: 'products', loadChildren: 'path/to/products/module' }
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules, useHash: true })],
  exports: [RouterModule],
  declarations: [NotFoundComponent]
})

ProductRoutingModule看起来像这样:

const routes: Routes = [
  { path: '', component: ProductsComponent },
  { path: 'type1', loadChildren: 'path/to/Type1product/module' },
];

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

所有组件都加载到顶级路由器插座中 . 我期望在产品路由器插座中加载type1模块 .

2 回答

  • 1

    如果我正确理解您的问题,您希望组件 TypeProduct1TypeProduct2 进入 <router-outlet> ProductsComponent . 如前所述,儿童路线可能是解决方案 .

    我认为您的AppRoutingModule应该编辑为:

    // AppRoutingModule
    const routes:Route = [
      { path: 'customers', loadChildren:'/path/to/customers/module' },
      { path: 'pricing', loadChildren:'/path/to/pricing/module' }
      { 
        path: 'products',
        loadChildren: 'path/to/products/module',
        children: [
          { path: 'type1', loadChildren: 'path/to/Type1product/module' },
          { path: 'type2', loadChildren: 'path/to/Type2product/module' },
        ]
      }
    ];
    
  • 1

    要正确使用模块的概念,仍应在ProductRoutingModule中定义路径 . 您只需进行一次小编辑即可 . 您应该将延迟加载的路由定义为空路由的子项 .

    ProductRoutingModule

    const routes: Routes = [
      { path: '', component: ProductsComponent, 
        children: [
            { path: 'type1', loadChildren: 'path/to/Type1product/module' },
            { path: 'type2', loadChildren: 'path/to/Type2product/module' }
        ]}
    ];
    
    @NgModule({
      imports: [RouterModule.forChild(routes)],
      exports: [RouterModule]
    })
    

    更新

    如果您在延迟加载的组件中命名了路由,请不要使用如图所示的空路由 . 这是一个角度已知的bug,可以在这里跟踪:Github: Lazy load auxilary #10981

相关问题