Angular懒加载模块的子路由未能加载

7

我不确定我是否做得正确。问题是:当我从延迟加载模块导航到某些组件的子路由时,它根本没有加载。它重新加载了来自延迟加载模块的主页组件。

app-routing.component.ts

const routes: Routes = [
  {path: 'intel', loadChildren: () => import(`./intel/intel.module`).then(m => m.IntelModule)},
  {
    path: 'planet-detector',
    loadChildren: () => import('./planet-detector/planet-detector.module').then((m) => m.PlanetDetectorModule)
  },
  {path: '', redirectTo: 'space', pathMatch: 'full'},
  {path: '**', component: BlackHoleComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

planet-detector-routing.module.ts

const routes: Routes = [
  {path: '', component: DetectorComponent, children: [
      { path: 'first', component: FirstChildComponent},
      { path: 'second', component: SecondChildComponent}
    ]}
];

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

在上面的示例中,当您输入:“'http://localhost:4200/planet-detector/first'”时,它会加载DetectorComponent组件而不是FirstChildComponent(URL指向“http://localhost:4200/planet-detector/first”)。
我注意到当我将PlanetDetectorRoutingModule更改为:
const routes: Routes = [
  { path: '', component: DetectorComponent },
  { path: 'first', component: FirstChildComponent },
  { path: 'second', component: SecondChildComponent }
];

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

那么它可以正常工作。还有可能有一个问题,这些子路由分离的好处是什么?

1个回答

9

当在children属性中声明路由时,意味着它们应该作为该组件的子元素进行渲染。

因此,要呈现该路由,需要在DetectorComponent中存在一个<router-outlet>

列在children中的路由遵循以下规则:

路由器对待这些子路由的方式有重要的区别。

路由器会在ParentComponent的RouterOutlet中显示这些路由的组件,而不是在AppComponent shell的RouterOutlet中显示。


很高兴我能帮到你,你能否也接受这个答案呢 :) https://stackoverflow.com/help/someone-answers - C.OG

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接