I encountered a circular dependency issue in my Angular project and tried various solutions, including exporting all dependent classes from a "single file" as suggested here. Unfortunately, this approach did not work for me. I then explored other solutions such as using dependency injections, following the guidance provided in these links:
How to solve the circular dependency Services depending on each other
Despite implementing dependency injections, I am still encountering exceptions in my code. Below is a snippet of the affected code:
moduleA.ts
import { MODULE_B_NAME } from "./moduleB";
import { Injectable, Injector } from "@angular/core";
export const MODULE_A_NAME = 'Module A';
@Injectable({
providedIn: 'root'
})
export class ModuleA {
private tempService: any;
constructor(private injector: Injector) {
setTimeout(() => this.tempService = injector.get(MODULE_B_NAME));
}
public getName(): string {
this.tempService.getName();
return "we are forked";
}
}
moduleB.ts
import { MODULE_A_NAME } from "./moduleA";
import { Injectable, Injector } from "@angular/core";
export const MODULE_B_NAME = 'Module B';
@Injectable({
providedIn: 'root'
})
export class ModuleB {
private tempService: any;
constructor(private injector: Injector) {
setTimeout(() => this.tempService = injector.get(MODULE_A_NAME));
}
public getName(): string {
//this.tempService = this.injector.get(MODULE_A_NAME);
this.tempService.getName();
return "we are forked";
}
}
appComponent.ts
import { Component } from '@angular/core';
import { ModuleA } from './moduleA';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'test01';
getSomething() {
return ModuleA.name;
}
}
appModules.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ModuleA } from './moduleA';
import { ModuleB } from './moduleB';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [ModuleA, ModuleB],
bootstrap: [AppComponent]
})
export class AppModule { }
If someone could kindly review the code and help identify what might be causing the issue, it would be greatly appreciated.