1. providedIn: ‘root’
The @Injectable() decorator has the providedIn metadata option, where you can specify the provider of the decorated service class with the root injector, or with the injector for a specific NgModule.
对于一个服务OneService,如果只是在懒加载模块CustomersModule中被使用,providedIn:‘root’ 可以如我们设想的工作:即把OneService和懒加载的模块打包在一起,如此减少代码首次的下载量。看来angular还挺智能的。
2. providedIn:某懒加载模块
2.0 循环依赖问题
懒加载这个模块CustomersModule,CustomersModule里面有个组件CustomerListComponent,CustomerListComponent注入了OneService,
// OneService
@Injectable({
providedIn: CustomersModule
})
这个时候,我们会看到这样的警告:
WARNING in Circular dependency detected:
src\app\customers\customer-list\customer-list.component.ts -> src\app\one.service.ts
-> src\app\customers\customers.module.ts -> src\app\customers\customer-list\customer-list.component.ts
,导航到懒加载模块的时候也会看到这样的错误:
2.1 解决方法
就是打破循环依赖,创建一个模块OneModule,在其中提供OneService;然后导入到懒加载的模块CustomersModule中。
// CustomersModule
@NgModule({
imports: [
OneModule
],
declarations: [CustomerListComponent]
})
export class CustomersModule { }
// OneModule
import { NgModule } from '@angular/core';
@NgModule({
})
export class OneModule { }
// OneService
@Injectable({
providedIn: OneModule
})
export class OneService {
constructor() {
console.log(123456789);
}
}
OneService 可以在OneModule被提供,而CustomersModule导入了OneModule,这样就没有了循环依赖了。
参考文献:
https://angular.io/guide/dependency-injection
https://medium.com/@tomastrajan/total-guide-to-angular-6-dependency-injection-providedin-vs-providers-85b7a347b59f
https://upgradetoangular.com/angular-news/providedin-the-angular-6-attribute-you-must-start-using/