面试题答案
一键面试- 创建懒加载模块:
- 使用Angular CLI命令创建一个新模块,例如:
ng generate module lazy - - route lazy - - module app.module
。这里lazy
是模块名,--route
指定路由路径,--module
指定该懒加载模块属于哪个根模块。
- 使用Angular CLI命令创建一个新模块,例如:
- 配置路由:
- 在懒加载模块的路由文件(如
lazy - routing.module.ts
)中配置该模块的路由。例如:
- 在懒加载模块的路由文件(如
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
{
path: '',
component: // 这里填写该模块默认展示的组件
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class LazyRoutingModule { }
- 在主路由模块中配置懒加载:
- 在主路由模块(如
app - routing.module.ts
)中,将懒加载模块配置为路由的loadChildren
。例如:
- 在主路由模块(如
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
{
path: 'lazy',
loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule)
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
关键代码总结:
- 懒加载模块路由文件:
RouterModule.forChild(routes)
用于配置子路由。 - 主路由模块:
loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule)
使用动态导入实现懒加载,只有在访问到/lazy
路径时才会加载LazyModule
模块。