簡體   English   中英

在 angular 中,使用 providedIn 和 forRoot 時的循環依賴

[英]in angular, Circular dependency when using providedIn and forRoot

我正在開發一個 angular 庫。 它有一個內部服務。 定義如下。 使用providedIn是可搖樹的。 並且沒有使用providedIn:'root' ,因為它是內部的並且僅在模塊scope中使用。

@Injectable({
  providedIn: MyChartModule,
})
export class LineChartLibService {

當我想在模塊定義中添加forRoot以在延遲加載中只有一個實例時,它會遇到循環依賴。

export class MyChartModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: MyChartModule,
      providers: [LineChartLibService],
    };
  }
}

在這種情況下我們應該怎么做? 是否可以在庫中提供延遲加載的可搖樹服務?

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

我之前回答了一個(非重復的)問題,該問題為您提供了這種方法的替代方案。

https://stackoverflow.com/a/60377431/5367916

采取這個設置:

我的模塊.ts

declarations: [
  MyComponent
]

我的服務.ts

@Injectable({ providedIn: MyModule })

我的組件.ts

constructor(private myService: MyService) {}
  • 我的服務導入我的模塊
  • 我的模塊導入我的組件
  • 我的組件導入我的服務

存在循環依賴。

一種解決方法

解決方法是創建一個服務模塊並將其導入到您的模塊中。

我的模塊.ts

imports: [
  MyModuleServices
],
declarations: [
  MyComponent
]

我的模塊服務.ts

// no imports or declarations

我的服務.ts

@Injectable({ providedIn: MyModuleServices })

我的組件.ts

constructor(private myService: MyService) {}

選擇

更直接的方法是將服務添加到模塊的提供程序中。

@NgModule({
  providers: [ MyService ]
})
export class MyModule {}

我認為會發生以下情況:

  1. 您有可能需要 LineChartLibService 的 line-chart.component.js。
  2. 在 LineChartLibService 中,您說這個 Injectable 是在 MyChartModule 中提供的。
  3. 在 MyChartModule 中,您可能將 line-chart.component.js 聲明為該模塊的一部分。

這意味着模塊請求組件,組件請求服務,模塊請求模塊,然后模塊再次請求組件:循環依賴。

如果您在問題中添加更多代碼和上下文,我們可能會提出更好的建議;-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM