Angular 6: forChild回退路由覆盖子路由

Angular 6: forChild fallback route overwrites child route

正如您在那个 stackblitz 中看到的那样,我对 forRoot/forChild 路线有点困惑:

https://stackblitz.com/edit/hello-angular-6-thzmnv

在根模块中定义了路由'sub-route':

const routes: Routes = [
  {
    path: 'sub-route',
    loadChildren: () => SubModule,
  },
];

@NgModule({
  imports:      [
    BrowserModule,
    SubModule,
    RouterModule.forRoot(routes),
    SubRoutingModule
  ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})

在子路由器模块中定义了fellowing routes:

const routes: Routes = [
  {
    path: '',
    component: SubComponent,
  },
  {
    path: 'first',
    component: SubComponent,
    data: { index: 1 },
  },
  {
    path: 'second',
    component: SubComponent,
    data: { index: 2 },
  },
  {
    path: '**',
    redirectTo: 'first',
  }
];

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

我不明白为什么回退路线 ** 没有按预期工作。

例如,

导航到 /sub-route/second 将重定向到 /first。如果定义了合适的路线,为什么要进行重定向?如果由于某种原因发生了重定向,为什么不重定向到 /sub-route/first 而只是重定向到 /first?谢谢!

也许你可以试试这个

 {
    path: '**',
    redirectTo: '/sub-route/first',
  }

由于延迟加载,从 AppModule 中删除 SubRoutingModule 和 SubModule,并将 SubRoutingModule 添加到 SubModule 内部。

import { NgModule } from '@angular/core';
import { SubComponent } from './sub.component';
import { SubRoutingModule } from './sub-routing.module';

@NgModule({
  declarations: [
    SubComponent
  ],
  imports: [
    SubRoutingModule
  ],
  exports: [
    SubComponent
  ],
})
export class SubModule {}

然后也给子模块添加一个路由器插座。

<router-outlet></router-outlet>
sub-component<br>
index: {{index}}