在 Angular 7 中检测到循环依赖

Circular dependency detected in Angular 7

我的 Angular 7 应用程序中有以下应用程序结构:

AppModule
DashboardModule
  DashboardChild1
  DashboardChild2
  DashboardChild3
  DashboardService
AdminModule
  AdminChild1
  AdminChild2
  AdminChild3

并且我希望 DashboardService 仅在 DashboardModule 中可用,所以我遵循了这个 link providedin-and-ngmodules.

这是我的 DashboardService:

import { Injectable } from '@angular/core';
import { DashboardModule } from './dashboard.module';

@Injectable({
  providedIn: DashboardModule
})
export class DashboardService {
  .......
}

我在 DashboardChild1 组件中使用了该服务,但出现以下错误:

WARNING in Circular dependency detected: src/app/dashboard/dashboard-child1/dashboard-child1.component.ts -> src/app/dashboard/dashboard.service.ts -> src/app/dashboard/dashboard.module.ts -> src/app/dashboard/dashboard-routing.module.ts -> src/app/dashboard/dashboard-child1/dashboard-child1.component.ts

WARNING in Circular dependency detected: src/app/dashboard/dashboard-routing.module.ts -> src/app/dashboard/dashboard-child1/dashboard-child1.component.ts -> src/app/dashboard/dashboard.service.ts -> src/app/dashboard/dashboard.module.ts -> src/app/dashboard/dashboard-routing.module.ts

WARNING in Circular dependency detected: src/app/dashboard/dashboard.module.ts -> src/app/dashboard/dashboard-routing.module.ts -> src/app/dashboard/dashboard-child1/dashboard-child1.component.ts -> src/app/dashboard/dashboard.service.ts -> src/app/dashboard/dashboard.module.ts

WARNING in Circular dependency detected: src/app/dashboard/dashboard.service.ts -> src/app/dashboard/dashboard.module.ts -> src/app/dashboard/dashboard-routing.module.ts -> src/app/dashboard/dashboard-child1/dashboard-child1.component.ts -> src/app/dashboard/dashboard.service.ts

我在这里错过了什么?

以来最有可能发生这种情况

DashboardChild1 是 DashboardModule 的成员,DashboardChild1 试图通过注入访问 DashboardModule。结果是循环依赖。

DashboardModule calls DashboardChild1 
DashboardChild1 calls DashboardModule
DashboardModule class DashboardChild1
DashboardChild1 calls DashboardModule
...
...
...
...

同样适用于DashboardService

DashboardModule calls DashboardChild1 calls DashboardService
DashboardService calls DashboardModule
DashboardModule calls DashboardChild1 calls DashboardService
DashboardService calls DashboardModule
...
...
...
...

如本博客中所示 post:https://medium.com/@tomastrajan/total-guide-to-angular-6-dependency-injection-providedin-vs-providers-85b7a347b59f

您可以将 DashboardService 拉出到它自己的模块 DashboardServiceModule 中。然后将其导入 DashboardModule 并在您的 DashboardChild(ren).

中使用它