Exciting News!! Angular 10 Update: Detecting a Circular Dependency When Injecting a Service into a Specific Module. What Sets @Inject Apart from providers[ ]?

I'm trying to integrate my countries.service into my pricing.module and utilize it within the list-pricing component of that module. However, I encountered a circular dependency issue. https://i.sstatic.net/iNepg.jpg

This is how my module looks like

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { PricingRoutingModule } from './pricing-routing.module';
import { DetailsPricingComponent } from './details-pricing/details-pricing.component';
import { ListPricingComponent } from './list-pricing/list-pricing.component';



@NgModule({
  declarations: [DetailsPricingComponent, ListPricingComponent],
  imports: [
    CommonModule,
    PricingRoutingModule,
  
  ],
})
export class PricingModule { }

https://i.sstatic.net/xFnAp.jpg
Here is the list-pricing component from my module

import { Component, OnInit } from '@angular/core';
import { Post } from 'src/app/Interfaces/post';
import { CountriesService } from 'src/app/services/countries.service';
@Component({
  selector: 'app-list-pricing',
  templateUrl: './list-pricing.component.html',
  styleUrls: ['./list-pricing.component.css'],
})
export class ListPricingComponent {
  result:Array<Post>;
  constructor(private service:CountriesService) { }

  ngOnInit(): void {  
     this.service.getCountries().subscribe(data=> 
        {  
     console.log("hello") 
          this.result=data;

      })    

 }
}

https://i.sstatic.net/UKR34.jpg Pricing-routing.module content

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DetailsPricingComponent } from './details-pricing/details-pricing.component';
import { ListPricingComponent } from './list-pricing/list-pricing.component';

const routes: Routes = [
  { path: '', component: ListPricingComponent },
  { path: 'detailsPricing', component: DetailsPricingComponent },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class PricingRoutingModule {}

https://i.sstatic.net/RUnHg.jpg Error Encountered: https://i.sstatic.net/DqJYx.jpg

UPDATE !! I managed to resolve the issue by switching the syntax from @Injectable({ provideIn:....}) in the service to using providers [] in my module instead. Still uncertain about the difference between them though.

Answer №1

While scrolling through the depths of Angular github, I came across an intriguing issue that caught my attention. It seems like a circular dependency check is causing some trouble. One solution proposed was to add providers:[CountriesService] in pricing.module.ts.

Alternatively,

You could create a new module to tackle this circular dependency check enforced by the TypeScript compiler.

Personally, I'd recommend sticking with the providers syntax instead of diving into creating a whole new module.

Answer №2

Typically, in about 99% of cases, the providedIn value should be 'root' to ensure tree shakeability. This means that if a service is not used anywhere in the app, it will not be included in the final compiled bundle.

If a service has application scope, use the following syntax:

@Injectable({
  providedIn: 'root',
})
export class CustomService {
}

For module scope, add the service to the providers array of the module.

import { Injectable, NgModule } from '@angular/core';

@Injectable()
export class Service {
  doSomething(): void {
  }
}

@NgModule({
  providers: [Service],
})
export class ServiceModule {
}

Remember to replace the module and service names with your own.

For component scope, include the service in the component metadata.

Useful links : https://angular.io/guide/dependency-injection-providers#creating-tree-shakable-providers

Answer №3

You can attempt eliminating

import {PricingModule} from '../pricing/pricing.module'; 

from countries.service, as it appears to be the root of the circular dependency issue.

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

An effective way to prevent right-clicking on iframes across all websites

I am facing an issue with disabling right click for the iframe. I've successfully disabled it for the default URL of the IFrame, but when displaying any other webpage, the right click remains usable. Below are the sample codes I have used: document.o ...

Is it better to use AngularJS' ngMock inject before each test or for each individual test case?

Current Situation As I work on writing tests for an Angular project, I have come across a common practice of creating "global" variables in a describe block to store dependencies needed for the tests. This approach involves defining variables like $contro ...

Retain annotations for assigned types in d.ts files

When compiling declarations for the code snippet below using Typescript v5.0.4, I encounter an issue: type SomeType<T> = { field: T; }; const getInstance = <T>( value: T ): SomeType<{ [K in keyof T]: T[K]; }> => { return { ...

Next.js: An absence of response is observed when a high volume of requests is made on a server-side rendering page with

Currently, I am utilizing Next.js along with a custom server (express js) as demonstrated in the GitHub example. For instance, I have a page located at “/post/[id]” that makes use of Next.js dynamic routing. The issue arises when the number of request ...

Using aliased imports is no longer an option when setting up a new TypeScript React application

Upon creating a new React-typescript app using the following command with <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3143545052457100061f011f03">[email protected]</a> and <a href="/cdn-cgi/l/email-protectio ...

If the width of the table is set to 100% in the CSS, the legend in the Flot chart will automatically shift to the

When the CSS for the table is set to { width:100%}, the Flot chart's legend moves to the left side. Is there any way to maintain the table { width:100%} while also preventing this shift, considering that the CSS is applied site-wide? Here is a jsfid ...

Do you need to discontinue a live connection?

Currently, I am in the process of setting up a notification system using StopmJs within React. To gather the count of new messages and the message list, I have subscribed to two destinations. I am curious if there will be any memory leaks if I decide not ...

What is the best way to determine if a variable exists within an array in Angular and JavaScript?

Currently, I am working on a project using Angular 6 with Laravel. In one part of my code, I am fetching an array in the frontend and need to check if a certain variable is present within that array. In PHP, you can easily achieve this using the in_array f ...

When you scroll a fixed element on the page, the block is truncated

I made a modification for adding cart items and included a script for managing my cart The cart is supposed to stick to the right edge and scroll up and down on the page Everything seems to work, but there's a slight issue when I click on Add 1 and ...

Achieving the mat-primary color in Angular Material 18

After successfully upgrading my Angular-16 project to angular-18, everything seems to be working fine including the upgraded Angular material-18. My current challenge is assigning a primary color to certain elements. The syntax I have been using looks som ...

The i18next.t function is returning an undefined value

I am experiencing an issue with my application's routes, as the .js file that contains them seems to be causing the problem: import i18n from "i18next"; const dashRoutes = [ // ... { path: "/user-profile", navbarName: ...

Collaboratively accessing a shared constant in two separate JavaScript files

I am diving into the world of JavaScript and Node.js. I am currently experimenting with Puppeteer to extract the text value of a tag and store it in a constant variable. However, I am encountering difficulties when trying to integrate this value into my ...

Utilizing PrimeNG radio buttons for selecting multiple items simultaneously

While dynamically creating multiple radio buttons using *ngFor, I am facing an issue where I can select multiple items from the UI. Below is my code snippet: <div class="p-col-12"> <p>Question Type</p> <div *ngFor ...

Is it possible to utilize multiple useMutation hooks within a single component?

I'm curious about how to utilize multiple mutations in a component effectively. For instance, if I need to both create and update the same component, how can I achieve this? Here's an example: const [createUser, {data}] = useMutation(CREATE_US ...

Differences between HTML Markup in PHP and Javascript

I have been working on various tasks involving AJAX requests to fetch data from the backend of my website when a thought crossed my mind. Is it more efficient to style the HTML in PHP before sending it to the client, or should I send the data as JSON and t ...

Implementing object binding for multiple properties in Angular: A comprehensive guide

When using Vue.js <Person v-bind='{name: "Tom", color: "Blue"}'></Person> If working with React <Person {...{name: "Tom", color: "Blue"}}></Person> How about Angular? LATEST The ...

What is the best way to delete a CSS class from a specific element in a list using React?

I need to implement a functionality in React that removes a specific CSS class from an item when clicking on that item's button, triggering the appearance of a menu. Here is my code snippet. import "./Homepage.css" import React, { useState, ...

"Encountering a blank page in React Router when transitioning between separate projects

I've come across some discussions about a similar issue like this one, but I haven't been able to resolve my problem. In my initial project, I can smoothly navigate between its pages. However, when I created a second project hosted in a subdirec ...

An issue occurred when trying to access the version information from http://localhost:8088/web/webclient/version_info while logging in to the Odoo server using

While attempting to log in with my Ionic app to an Odoo server, I encountered the following error message. Is this due to CORS, and how can I configure my local Odoo server without using Nginx? XMLHttpRequest cannot load http://localhost:8088/web/webcli ...

Different ways to incorporate the div element with text content as opposed to images in ngx-slick-carousel

I am looking to incorporate multiple <div> elements with content into the ngx-slick-carousel in my Angular 12 application. Currently, the carousel is displaying placeholder images and I am unsure of how to replace these images with div elements. Her ...