Uh-oh! A circular dependency has been detected in the Dependency Injection for UserService. Let's untangle this web and fix the issue!

Encountering the following error: "ERROR Error: Uncaught (in promise): Error: NG0200: Circular dependency in DI detected for UserService."

The auth.component.ts utilizes the UserService and User classes, while the user.service.ts only uses the User class.

The origin of the circular dependency is unknown.

User.model.ts:

export class User{
    constructor(public login: string,
                public Mdp : string){
    }
}

User.Service.ts :

import 'rxjs/RX';
import { User } from '../models/User.model';
import { Subject } from 'rxjs';
import { Injectable } from '@angular/core';

@Injectable()

export class UserService {
  private users!: User[];
  userSubject = new Subject<User[]>();

  constructor(private userService: UserService) {
  }

  emitUsers() {
    this.userSubject.next(this.users.slice());
  }

  addUser(user: User) {
      this.users.push(user);
      this.emitUsers();
  }

  logUser(){
    console.log("la");
  }
}

auth.component.ts:

import { ThisReceiver } from '@angular/compiler';
import 'rxjs/RX';
import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormArray } from '@angular/forms';
import { Router } from '@angular/router';

import { User } from '../models/User.model';
import { Subscription } from 'rxjs/Subscription';
import { UserService } from '../services/user.Service';


@Component({
  selector: 'app-auth',
  templateUrl: './auth.component.html',
  styleUrls: ['./auth.component.scss']
})
export class AuthComponent implements OnInit, OnDestroy {
  
  users: User[] = [];
  userSubscription: Subscription = new Subscription;
  userForm!: FormGroup;
   
  constructor( 
    private UserService: UserService,
    private formBuilder: FormBuilder,
    private router : Router
    ) {}

    ngOnInit() {
      this.initForm();
    }
  
    initForm(){
      this.userForm = this.formBuilder.group({
        login:['',Validators.required],
        Mdp:['',Validators.required],
      });
    }
  
    onSubmitForm(){
      const formValue= this.userForm.value;
      const newUser = new User (
        formValue['login'],
        formValue['Mdp']
      );
  
        console.log(newUser);
  
        this.UserService.logUser();
    }
  
    ngOnDestroy() {
      this.userSubscription.unsubscribe();
    }

}

Grateful for any guidance on resolving this issue.

Answer №1

It appears that you are injecting UserService into itself within the code snippet provided. This may indicate a mistake where you intended to inject a different service, or perhaps no injection was needed at all.

export class UserService {
  private users!: User[];
  userSubject = new Subject<User[]>();

  constructor() {}
  //...
}

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

What is the process for updating the background color of the header in ngx datatable?

I am looking to change the background color of the table header to blue. This is the HTML code I have: <ngx-datatable class="material" [rows]="rows" [columnMode]="'force'" [headerHeight]="50" [footerHe ...

Tips for converting NULL% to 0%

When running my calculatePercents() method, I am receiving NULL% instead of 0%. Upon checking my console.log, I noticed that the values being printed are shown as NULL. calculatePercents() { this.v.global.total.amount = this.v.global.cash.amount + ...

Dealing with the error "Type 'date[]' is not assignable to type '[date?, date?]' in a React hook

I'm attempting to assign a date range but encountering an error that states: Type 'Date[]' is not assignable to type '[Date?, Date?]'. Types of property 'length' are incompatible. Type 'number' is not assignab ...

Storing data in GridFS with MongoDB from an express buffer

Currently, I am attempting to save an Image file that I'm sending as multipart in my MongoDB utilizing GridFS. My approach involves using multer with the memoryStorage option. let upload = multer({ storage: multer.memoryStorage() }).single('ima ...

Elements that allow for asynchronous data submission without requiring a traditional submit button

Hey there, I could really use some help with this puzzle I'm trying to solve. Here's the situation: <ul> <li>Number: <span id="Number">123</span></li> </ul> I want to set up a connection between t ...

Error encountered during installation of Nativescript Post Install Script

While I am comfortable running one of our current projects with Nativescript, I encountered an error when attempting to install it on a new project using the following command: sudo ng new --collection=@nativescript/schematics the-juice-box --shared The ...

What is the best way to swap out the if else statement with a Ternary operator within a JavaScript function?

Is there a way to replace the if else statement in the function using a Ternary operator in JavaScript? private getProductName(productType: string): string { let productName = 'Product not found'; this.deal.packages.find(p => p.isSele ...

Tips for updating state in React TypeScript 2.0?

Working with a small component built using React and TypeScript has presented a unique challenge. interface Props { } interface State { isOpen: boolean; } class App extends React.Component<Props, State> { constructor(props: Props) { super ...

The Angular CLI release does not match the Angular version

After updating Angular to version 9, my previously smoothly running angular project started throwing this error: This peculiar error message popped up: This version of CLI is only compatible with Angular versions 0.0.0 || ^10.0.0-beta || >=10.0.0 <1 ...

Is it possible to display Angular Material Slider after the label?

Searching through the Angular Material docks, I came across the Sliders feature. By default, the slider is displayed first, followed by its label like this: https://i.sstatic.net/C5LDj.png However, my goal is to have the text 'Auto Approve?' sh ...

NgFor is failing to display data from a fully populated array of objects

CLICK HERE FOR THE IMAGE So, let's tackle the issue at hand. I have an array that contains data fetched from an API. These data points are essentially messages. Now, below is the TypeScript file for a component where I aim to display all these messag ...

Input for uncomplicated changing identifier

I am looking to create types for dynamic keys that will be of type number. I have two similar types defined as follows: type UseCalculatePayments = () => { totalPayments: number; aggregate: number; condition: boolean; }; type UseCalculateCommissio ...

Organize elements within an array using TypeScript

I have an array that may contain multiple elements: "coachID" : [ "choice1", "choice2" ] If the user selects choice2, I want to rearrange the array like this: "coachID" : [ "choice2", "choice1" ] Similarly, if there are more tha ...

Troubleshooting a 400 error when trying to authenticate with Firebase using AngularFire2

Authentication through Google has been enabled in the console: https://i.sstatic.net/Kkdh3.png Here is the login code: import { Component, OnInit } from '@angular/core'; import { AngularFire, AuthProviders } from 'angularfire2'; @Com ...

Encountering issues while attempting to use npm to clone a

One of my projects in GitLab is a dependency for others. To access it as a private package, I set up a project access token and added the following line to the dependent project's packages.json: "private-project": "git+https://npm:< ...

Unable to globally override the default font in MUI theme

Objective: My goal is to customize the default font in MUI themes. Issue: Despite reviewing MUI documentation and conducting research on Stack Overflow, I am facing difficulty overriding a custom font globally across my theme. Theme setup: import { creat ...

Tips for simulating the getCustomRepository function in typeORM

I am facing a challenge in unit-testing a class that has a getCustomRepository method in its constructor. I'm struggling to find an easy way to mock it. Below is the code for my class: import {getCustomRepository} from 'typeorm'; export cl ...

What exactly are the implications of having dual type declarations in TypeScript?

I recently came across the Angular tutorial here In the code snippet below, there are double type declarations that I am having trouble understanding. handleError<T>(operation = 'operation', result?: T) { return (error: any): Observabl ...

Guide to developing universal customized commands in Vue 3 using Typescript

I recently built my app using the Vue cli and I'm having trouble registering a global custom directive. Can anyone point out what I might be doing incorrectly here? import { createApp } from "vue"; import App from "./App.vue"; impo ...

One way to ensure a necessary check on the mat-expansion-panel

Currently, I am working on a form that includes an upload panel (mat-expansion-panel) for uploading documents. My goal is to indicate that this panel is required by adding an asterisk (*) next to it. While I know how to add the asterisk to <textarea&g ...