我以 Angular 的“延迟加载功能模块”为例: live demo
CustomersModule是一个延迟加载模块,我在客户模块中创建了一个测试服务。
const routes: Routes = [
{
path: 'customers',
loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
},
{
path: 'orders',
loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule)
},
{
path: '',
redirectTo: '',
pathMatch: 'full'
}
];
import { Injectable } from '@angular/core';
@Injectable()
export class TestService {
constructor() { }
getHeroes() { return "HEROES"; }
}
在 CustomersModule 中,将其添加到提供程序:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CustomersRoutingModule } from './customers-routing.module';
import { CustomersComponent } from './customers.component';
import {TestService} from "./test.service";
@NgModule({
imports: [
CommonModule,
CustomersRoutingModule
],
providers: [
TestService
],
declarations: [CustomersComponent]
})
export class CustomersModule { }
CustomersModule 也有一个CustomersComponent,通过这种方式我可以在其中使用 TestService。
import { Component, OnInit } from '@angular/core';
import {TestService} from "./test.service";
@Component({
selector: 'app-customers',
templateUrl: './customers.component.html',
styleUrls: ['./customers.component.css']
})
export class CustomersComponent implements OnInit {
testService: TestService;
constructor(test: TestService) {
this.testService = test;
}
ngOnInit() {
}
test(){
console.log(this.testService.getHeroes());
}
}
但是当我从CustomersModule的提供者数组中删除TestService并在TestService中使用providedIn时:
import { Injectable } from '@angular/core';
import {CustomersModule} from "./customers.module";
@Injectable({
providedIn: CustomersModule
})
export class TestService {
constructor() { }
getHeroes() { return "HEROES"; }
}
我收到了这个错误:
core.js:6228 ERROR Error: Uncaught (in promise): ReferenceError: Cannot access 'CustomersModule' before initialization
ReferenceError: Cannot access 'CustomersModule' before initialization
at Module.CustomersModule (customers.component.ts:9)
at Module../src/app/customers/test.service.ts (test.service.ts:5)
at __webpack_require__ (bootstrap:84)
at Module../src/app/customers/customers.component.ts (customers-customers-module.js:78)
at __webpack_require__ (bootstrap:84)
at Module../src/app/customers/customers-routing.module.ts (customers-customers-module.js:29)
at __webpack_require__ (bootstrap:84)
at Module../src/app/customers/customers.module.ts (customers.component.ts:9)
at __webpack_require__ (bootstrap:84)
at ZoneDelegate.invoke (zone-evergreen.js:364)
at resolvePromise (zone-evergreen.js:798)
at resolvePromise (zone-evergreen.js:750)
at zone-evergreen.js:860
at ZoneDelegate.invokeTask (zone-evergreen.js:399)
at Object.onInvokeTask (core.js:41632)
at ZoneDelegate.invokeTask (zone-evergreen.js:398)
at Zone.runTask (zone-evergreen.js:167)
at drainMicroTaskQueue (zone-evergreen.js:569)
我知道这里有循环依赖,对于急切加载的模块,它可以工作,并且会启用 tree-shaking。这是否意味着在延迟加载模块中只能在 NgModule 中使用提供者数组?
有这方面的指导方针/最佳做法吗?