Search code examples
angularangular-servicesangular-ngmodelangular-module

Circular dependency detected in Angular 7


I have the following app structure in my Angular 7 app:

AppModule
DashboardModule
  DashboardChild1
  DashboardChild2
  DashboardChild3
  DashboardService
AdminModule
  AdminChild1
  AdminChild2
  AdminChild3

and I want to have DashboardService available only in the DashboardModule, so I followed this link providedin-and-ngmodules.

Here's my DashboardService:

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

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

I have used that service in DashboardChild1 component, but it is giving the following error:

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

what am I missing here?


Solution

  • This is most likely to happen since

    DashboardChild1 is a member of DashboardModule and DashboardChild1 trying to access DashboardModule by injectible. The result is Cirular Dependency.

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

    the same is also valid for DashboardService

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