@NgModule({ imports: [ CommonModule ], declarations: [TestDiComponent], exports: [TestDiComponent], providers: [ ] }) export class TestDIModule { static forRoot(): ModuleWithProviders { return { ngModule: TestDIModule, providers: [ TestDiService ] }; } }
在根模块中引入TestDIModule模块
imports: [ BrowserModule, TestDIModule.forRoot(), ],
最后在根模块路由中添加这个懒加载模块
const routes: Routes = [ { path: 'battery', loadChildren: './battery-widget/battery.widget.module#BatteryWidgetModule' }, ]; @NgModule({ exports: [ RouterModule ], imports: [ RouterModule.forRoot(routes) ], })
作为测试,可以在TestDIModule中的service中打log看一下
import { Injectable, ModuleWithProviders } from '@angular/core'; import { TestDIModule } from './test-di.module' @Injectable() export class TestDiService { constructor() { console.log('->TestDiService'); } addCoount() { this.count++; console.log('->count', this.count); } count = 0; }