I was facing circular dependency in angular project. I have come accross many solution including export all the dependent classes from "single file" as instructed here https://medium.com/visual-development/how-to-fix-nasty-circular-dependency-issues-once-and-for-all-in-javascript-typescript-a04c987cf0de It did't work. So I moved to different solution like using dependency injections as instructed in the following links:
How to solve the circular dependency Services depending on each other
But despite of using dependency injections, there are still exceptions. below is the 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 { }
Can someone pls look at the code and identity what is wrong with it thanks