Angular 5中的嵌套路由

8

我有以下模块结构:

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>

整个重点是以这样的方式将应用程序路由到 /index 组件,以通过 RooComponent --> AppComponent --> MainComponent --> IndexComponent
到目前为止,使用上述路由,AppComponent 被绕过了!
有什么想法吗?
谢谢。

你能在 StackBlitz 上重现这个问题吗? - Bunyamin Coskuner
1个回答

4

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

目前您的路由配置将按照以下方式工作:

  • 导航到/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'
    }]
  }]
}];

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