I am developing an angular library. it has an internal service. which is defined like below. Used providedIn
to be tree-shakable. and didn't use providedIn:'root'
because its internal and just used in the module scope.
@Injectable({
providedIn: MyChartModule,
})
export class LineChartLibService {
and when i wanted to add forRoot
in module definition to have just one instance in lazy loading, it encounter Circular dependency.
export class MyChartModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: MyChartModule,
providers: [LineChartLibService],
};
}
}
what should we do in this situations? is it possible to have a lazy load-able tree-shakable service in library?
WARNING: Circular dependency: dist\my-chart\esm2015\lib\my-chart.module.js -> dist\my-chart\esm2015\lib\line-chart\line-chart.component.js
-> dist\my-chart\esm2015\lib\line-chart-lib.service.js -> dist\my-chart\esm2015\lib\my-chart.module.js
I have previously answered a (non-duplicate) question that provides you with alternatives to this approach.
https://stackoverflow.com/a/60377431/5367916
Take this setup:
my-module.ts
declarations: [
MyComponent
]
my-service.ts
@Injectable({ providedIn: MyModule })
my-component.ts
constructor(private myService: MyService) {}
There is a circular dependency.
The workaround for this is to create a service module and import that into your module.
my-module.ts
imports: [
MyModuleServices
],
declarations: [
MyComponent
]
my-module-services.ts
// no imports or declarations
my-service.ts
@Injectable({ providedIn: MyModuleServices })
my-component.ts
constructor(private myService: MyService) {}
The much more straightforward way is to add the service to your module's providers.
@NgModule({
providers: [ MyService ]
})
export class MyModule {}
I think what happens is the following:
This means the module asks for the component, which asks for the service, which asks for the module which then asks for the component again: A circular dependency.
If you add more code and context to your question, we might be able to make a better suggestion;-)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.