Angular6 - 未加载空路径的子路由

Sal*_*jam 5 angular-routing angular

我正在将我的Angular 4应用程序转换为Angular 6.但是,我在进行与路由相关的更改时遇到了问题.

现在,当我运行我的应用程序时,Home组件已加载,但未加载ContentsComponent具有空路径的子组件.

我的应用程序中的路由定义如下:

app.routing.module.ts

const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'support', component: SupportComponent }
];

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

export class AppRoutingModule { }
Run Code Online (Sandbox Code Playgroud)

home.routing.module.ts

const routes: Routes = [
  {
    path: 'home', component: HomeComponent, 
    children: [
      { path: '', component: ContentsComponent }, //<-- This component is not loaded
      { path: '**', redirectTo: 'home' }
    ]
  }
];

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

export class HomeRoutingModule { }
Run Code Online (Sandbox Code Playgroud)

home.module.ts

@NgModule({
  imports: [
      HomeRoutingModule
      ],
  exports: [],
  declarations: [ HomeComponent, ContentsComponent ],
  providers: [],
})

export class HomeModule { }
Run Code Online (Sandbox Code Playgroud)

app.module.ts

@NgModule({
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule,
    HomeModule
  ],
  declarations: [AppComponent],
  bootstrap: [AppComponent],
  providers: [
    { provide: LocationStrategy, useClass: HashLocationStrategy }
  ]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)

home.component.html

<router-outlet></router-outlet>
Run Code Online (Sandbox Code Playgroud)

编辑:请注意我不想在/home网址部分后显示任何内容.

Chi*_*shi 0

对于子组件中的路由,您需要提及其名称。

将“/home”替换为“home”。

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'support', component: SupportComponent }
];

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

export class AppRoutingModule { }
Run Code Online (Sandbox Code Playgroud)

在 HomeRoutingModule 中,您无需再次提及“home”。

只需按如下方式命名子组件即可。

const routes: Routes = [
  {
    path: '', component: HomeComponent, 
    children: [
      { path: 'content', component: ContentsComponent },
      { path: '**', redirectTo: 'content' }
    ]
  }
];

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

export class HomeRoutingModule { }
Run Code Online (Sandbox Code Playgroud)

如果您不想在路由时更改路由路径,那么有两种选择

this.router.navigate(['/home/content'], { skipLocationChange: true });
Run Code Online (Sandbox Code Playgroud)

或者

const routes: Routes = [
      {
        path: '', component: HomeComponent, 
        children: [
          { path: '', redirectTo: 'content' }
          { path: 'content', component: ContentsComponent },
          { path: '**', redirectTo: 'content' }
        ]
      }
    ];
Run Code Online (Sandbox Code Playgroud)

有什么疑问就问我吧。谢谢。