简体   繁体   中英

in angular, Circular dependency when using providedIn and forRoot

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) {}
  • my-service imports my-module
  • my-module imports my-component
  • my-component imports my-service

There is a circular dependency.

A workaround

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) {}

Alternative

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:

  1. You have the line-chart.component.js that probably calls for the LineChartLibService.
  2. Within the LineChartLibService you say that this Injectable is provided in MyChartModule.
  3. Within the MyChartModule you probably declare the line-chart.component.js to be part of this module.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM