要在Angular 7中实现多个router-outlets和延迟加载,可以按照以下步骤进行操作:
创建一个名为app-routing.module.ts的新路由模块文件,并将其与主应用模块(例如app.module.ts)相关联。
在app-routing.module.ts文件中,导入RouterModule和Routes,并创建一个Routes数组来定义不同的路由。
在Routes数组中,使用loadChildren属性来延迟加载模块。例如,要延迟加载名为HomeModule的模块,可以使用以下代码:
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', loadChildren: './home/home.module#HomeModule' },
// 其他路由定义...
];
Routes数组中,为每个需要使用不同router-outlet的路由定义一个outlet属性。例如,要为名为primary的router-outlet定义路由,可以使用以下代码:const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', loadChildren: './home/home.module#HomeModule', outlet: 'primary' },
// 其他路由定义...
];
在app-routing.module.ts文件中,使用RouterModule.forRoot(routes)方法来配置路由。
在主应用模块(例如app.module.ts)中,导入RouterModule,并在imports数组中引入app-routing.module.ts文件。
在主应用模块的模板文件中,使用标签来定义主router-outlet。
在需要使用其他router-outlet的组件模板文件中,使用标签来定义其他router-outlet,并将name属性设置为定义在路由配置中的outlet属性值。
以下是一个完整的示例代码:
app-routing.module.ts文件:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', loadChildren: './home/home.module#HomeModule', outlet: 'primary' },
// 其他路由定义...
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
app.module.ts文件:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.html文件:
home.component.html文件:
Home Component
这样就可以在Angular 7中实现多个router-outlets和延迟加载。