在Angular 6中将急切加载转换为惰性加载的解决方法如下所示:
ng generate module lazy --route lazy --module app.module
这将在项目中创建一个名为lazy
的模块,同时在app.module.ts
中自动添加惰性加载的路由。
在惰性加载的模块中,您可以通过添加路由来指定想要进行惰性加载的组件。例如,在lazy.module.ts
中添加以下代码:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { LazyComponent } from './lazy.component';
const routes: Routes = [
{ path: '', component: LazyComponent }
];
@NgModule({
imports: [
CommonModule,
RouterModule.forChild(routes)
],
declarations: [LazyComponent]
})
export class LazyModule { }
在app.module.ts
中,将原来的急切加载的路由修改为惰性加载的路由。例如,如果您之前有一个急切加载的路由{ path: 'eager', component: EagerComponent }
,那么将其修改为:
{ path: 'eager', loadChildren: './lazy/lazy.module#LazyModule' }
这将告诉Angular在需要时惰性加载LazyModule
。
请注意,需要根据实际情况更改路径和模块名称。
现在,当访问/eager
路径时,Angular将惰性加载LazyModule
并显示LazyComponent
。
希望这可以帮助您将急切加载转换为惰性加载的解决方法。