在Angular 7

时间:2019-01-06 23:49:04

标签: angular angular-services angular-ngmodel angular-module

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

AppModule
DashboardModule
  DashboardChild1
  DashboardChild2
  DashboardChild3
  DashboardService
AdminModule
  AdminChild1
  AdminChild2
  AdminChild3

并且我希望DashboardService仅在DashboardModule中可用,因此我点击了此链接providedin-and-ngmodules

这是我的DashboardService

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

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

我已经在DashboardChild1组件中使用了该服务,但是它给出了以下错误:

  

警告:在循环依赖项中检测到:   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

     

警告:在循环依赖项中检测到:   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

     

警告:在循环依赖项中检测到:   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

     

警告:在循环依赖项中检测到:   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

我在这里想念什么?

2 个答案:

答案 0 :(得分:3)

最有可能发生自

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
...
...
...
...

答案 1 :(得分:0)

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

您可以将DashboardService放入其自己的模块DashboardServiceModule中。然后将其导入DashboardModule,并在您的DashboardChild(ren)中使用它。