Angular 5 中的嵌套路由

Nested routing in Angular 5

我有以下模块结构:

1-根模块

路由如下:

const routes: Routes = [
  { path: '', redirectTo: 'app', pathMatch: 'full' }
];

2- AppModule

路由如下:

const routes: Routes = [
   { 
        path: 'app', 
        component: AppComponent,
        children: [
            {
                path: '',
                redirectTo: 'index',
                pathMatch: 'full'
           }
       ]
   }

];

另外,AppModule导入了MainModule,它只是一个路由模块,配置如下:

const routes: Routes = [
    {
        path: '',
        component: MainComponent,
        children: [
            {
               path: 'index',
               loadChildren: '.\/..\/modules\/index\/index.module#IndexModule'
            },
            {
                path: '',
                redirectTo: 'index',
                pathMatch: 'full'
            }
       ]
  }

];

现在,RootComponent是起点:

@Component({
  selector: "app-root",
  template:  "<router-outlet></router-outlet>"
})
export class RootComponent implements OnInit {
  constructor() { }

  ngOnInit() {
 }
}

AppComponent定义为:

<router-outlet></router-outlet>
<app-quick-sidebar></app-quick-sidebar>

最后,MainComponent定义为:

<app-header-nav></app-header-nav>
<router-outlet></router-outlet>
<app-footer></app-footer>

重点是通过RooComponent-->AppComponent-->MainComponent-->[=将应用程序路由到/index组件25=]

至此,通过以上路由,AppComponent被绕过!

有什么想法吗?

谢谢

根据您当前的路由配置,MainComponent 未配置在 AppComponent 路径的子数组中。那么为什么它会出现在它的模板中呢?

现在您的路由配置将像这样工作:

  • 导航至 /app 将使您到达 AppComponent
  • 导航至 /index 将使您到达 IndexComponent

要实现 RooComponent --> AppComponent --> MainComponent --> IndexComponent 的预期行为,您的路由配置应如下所示:

const routes: Routes = [{ 
  path: '', 
  component: AppComponent,
  children: [{
    path: '',
    component: MainComponent,
    children: [{
      path: '', redirectTo: 'index', pathMatch: 'full'
    }, {
      path: 'index',
      loadChildren: '.\/..\/modules\/index\/index.module#IndexModule'
    }]
  }]
}];