Circular reference in Angular/TypeScript

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.

https://i.stack.imgur.com/eapk4.png

Answer №1

The issue arises from having the module name exports within the same file as the module itself. To rectify this, a separate file named module-names.const.ts should be created:

export const MODULE_A_NAME = 'Module A';
export const MODULE_B_NAME = 'Module B';

This new file can then be imported into both modules without causing a circular dependency:

import { MODULE_A_NAME } from "./module-names.const";

import { Injectable, Injector } from "@angular/core";

@Injectable({
  providedIn: 'root'
})
export class ModuleB {
  constructor(private injector: Injector) {
    setTimeout(() => this.tempService = injector.get(MODULE_A_NAME));
  }
}

It is important to consider the purpose behind these actions. It appears that the approach being taken may not align with best practices for Angular development (or any programming environment). After compilation using the --prod flag, the module names may change and the functionality implemented may no longer work as expected.

In this scenario, implementing a third service would be beneficial. This service could inject both service A and service B, allowing for better management of the desired actions.

Answer №2

Avoid using circular dependencies of the same type; it is advisable to utilize a service or interface for component collaboration instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript file slicing leads to generating an empty blob

I am currently working on a web-based chunked file uploader. The file is opened using the <input type="file" id="fileSelector" /> element, and the following simplified code snippet is used: $('#fileSelector').on('change', functio ...

The concept of matryoshka logic applied to data manipulation

"mainData"{ entities:[] }, "data2":{ entities:[ { name:"mainData": //entites }, { name:"mainData": //entites }, { name:"m ...

Each time I attempt to update my profile on the web application, I receive this notification

Working on creating a web app using react, redux, and node for managing profile data. I have a function that controls both creation and editing of profiles. The creation works fine, but I encounter an error message when trying to edit. I've reviewed m ...

Discover the steps to update the rows, adjust the number of results, and manage pagination in angular-datatable with an observable as the primary data source

Incorporating angular-datatables into my Angular 7 application has been a challenge, especially when it comes to displaying search results efficiently. Within the request-creation-component, a search form is generated. Upon clicking the submit button, an ...

Executing a Sequence of SQL Queries in Node.js

I am facing the challenge of performing nested queries to retrieve values from the database in order to generate a chart. The current approach involves executing a total of 12 queries, each aggregating the number of customers for every month of the year. ...

I am attempting to store the primary array in local storage, but unfortunately, the value is not being saved within the React context API

I attempted to store the main array in local storage and retrieve it as global state, but I am facing an issue where the data is not being saved in the local storage. This file represents my context. import { createContext, useReducer, ReactNode, FC, use ...

Using socket.io in a Django template without the need for the node.js service or socket.io.js file

I am working on a Django app that requires real-time push to clients. I have decided to use node.js and socket.io as it is considered the easiest platform for achieving this functionality. To implement this, I have included the socket.io framework code in ...

Having trouble retrieving an array element within an HTML table

Currently, I am working on a database project related to bar beer drinkers. To display the results of my queries on a local host website, I am running queries on my database and using Angular. The issue I am facing is that while I can see the query executi ...

WebApp specifically designed for iPads that mimics the functionality of a swipe

I am in the process of developing a full-screen web application for an iPad that will showcase a series of images in a slider format. The users should be able to swipe between the images and click on one to view it in detail. Below is an example showcasin ...

Unable to locate a React component module that has been published

After successfully publishing a React component to NPM, I encountered an issue when trying to use it in another project - I couldn't find the module! Module not found: Can't resolve 'react-subreddit-posts' in '/Users/kyle.calica/C ...

The functionality of getAttribute has changed in Firefox 3.5 and IE8, no longer behaving as it did before

Creating a JavaScript function to locate an anchor in a page (specifically with, not an id) and then going through its parent elements until finding one that contains a specified class. The code below works perfectly in Firefox 3.0 but encounters issues wi ...

Attempting to develop a filtering feature using ReactJS

Having some trouble with the if statement in my filter list function. Can't seem to figure out why it's not working properly. Here is the code snippet: filterList (event) { var updatedList = this.props.array; var filterText = this.stat ...

Tips for running code extracted from a JSON payload

I have a JSON string that contains HTML and JavaScript code. I want to display this code on a page in my React app, but instead of just showing it as a string, I want the HTML and JavaScript to be executed as if it were hard coded. Currently, the code is ...

I am unable to pass a variable through a callback, and I cannot assign a promise to a

Currently, I am facing a challenge with my code where I need to loop through a hard-coded data set to determine the distance from a user-entered location using Google's web API. The issue lies in passing an ID variable down through the code so that I ...

Tips for transferring data to the next page with JavaScript AJAX

I am working on a webpage that includes an html select element <pre> $query = mysql_query("select * from results"); echo "<select id='date' onchange='showdata()' class='form-control'>"; while ($arr = mysql_fetch_a ...

Encountering an issue while attempting to replicate the Spotify app on localhost:3000. The error message "TYPEERROR: Cannot read property 'url' of undefined" is hind

As a first-time user of stackoverflow, I am unfamiliar with its rules and regulations, so I apologize in advance for any mistakes I may make. Currently, I am attempting to create a Spotify clone using React. Everything was going smoothly until I completed ...

Steps for implementing drag-and-drop feature for a div in a template

I am looking to implement draggable functionality on a div element dynamically. The unique id for the div is generated using the code snippet below: var Exp=0; view.renderFunction = function(id1){ var id= id1 + Exp++; $("#"+id).draggable(); }; In my ...

What is the best way to implement an alert box in MVC without triggering a page redirection?

I have a specific requirement to display a custom alert box in order to confirm the user's intention to delete an item. Once the item is deleted, another alert box should appear confirming that the deletion was successful, prompting the user to click ...

Accessing a key from an AJAX JSON response and applying it within a .each() loop in jQuery

I'm struggling with a seemingly simple task that I just can't seem to get right. My goal is to convert multiple text inputs into select fields using AJAX and jQuery. Everything works smoothly, except when trying to make the $.each function dynam ...

Ways to shift placeholder text slightly to the right within a select dropdown?

Struggling with this issue for hours, I can't seem to figure out how to: Adjust the position of the placeholder text (Search) by 10 pixels to the right in my select component Reduce the height of the field (maybe by 5px) without success. Could someo ...